Vanilla Javascript - Cannot GET/route - ERROR - javascript

I am having problem in my routing.I used Vanilla javascript in routing and it worked but when I go from http://127.0.0.1:5500/ to http://127.0.0.1:5500/about and then refresh about page it says Cannot GET/about
My javascript code - router.js file
const rootDiv = document.getElementById("root");
let home = "";
let about = "";
let contact = "";
let profile = "";
/**
* #param {String} page
* #returns {String}
*/
const loadPage = async (page) => {
const response = await fetch(page);
const resHtml = await response.text();
return resHtml;
};
const loadAllPages = async () => {
home = await loadPage("home.html");
about = await loadPage("about.html");
contact = await loadPage("contact.html");
profile = await loadPage("profile.html");
};
const main = async () => {
await loadAllPages();
rootDiv.innerHTML = home;
routes = {
"/": home,
"/contact": contact,
"/about": about,
"/profile": profile,
};
};
main();
/**
* #param {String} pathname
*/
const onNavigate = (pathname) => {
window.history.pushState({}, pathname, window.location.origin + pathname);
rootDiv.innerHTML = routes[pathname];
};
window.onpopstate = () => {
rootDiv.innerHTML = routes[window.location.pathname];
};
Why I am getting this error??Can anyone please get me out of this.
All HTML files are in same directory.
Any help here would be very appreciated!!
Thanks!!

Related

Custom extension VS code- persistence state

I am tyring to keep the information in the sidebar in my vscode extention that I bulit, but I am not sure how to do that:
main code in the extention.js file:
context.subscriptions.push(vscode.window.registerWebviewViewProvider(
'viewId',
sidebarProvider(context)
));
main code in sidebarProvider.js:
const {sidebar} = require('./sidebar');
const sidebarProvider = (context) => {
return {
resolveWebviewView: (webviewView) => {
sidebar(webviewView, context);
},
};
};
module.exports = sidebarProvider;
main code in sidebar.js:
const vscode = require('vscode');
// severity, confidence, line number
const {handleMessageFromWebview} = require('./extenfuncs')
const fs = require('fs');
const sidebarhtml = String(fs.readFileSync(String(__dirname + "/siedbarwebviewhtml.html")))
const sidebar = function (webviewView, context) {
webviewView.webview.onDidReceiveMessage(
(message) => {
handleMessageFromWebview(message, webviewView.webview)
}, undefined,
context.subscriptions)
const html = sidebarhtml
webviewView.webview.options = {
enableScripts: true,
};
webviewView.webview.html = html;
};
module.exports = {sidebar}
I tried to use getState and setState but it didn't work

How can I download an array of URLs synchronously to maintain their order in React Native?

I'm using React Native and Firebase V9. I am trying to download URLs from storage, but I'm not able to both download all the URLs in the correct order and have them load the first time I visit the screen. I know that getDownLoadURL() runs asynchronously, which is why the images get downloaded in random order each time. There is something I'm not understanding correctly.
Here are two main ways I've tried:
const [memNameLogs, setMemNameLogs] = useState([]);
const [memIDLogs, setMemIDLogs] = useState([]);
const [memImagesLogs, setMemImagesLogs] = useState([]);
const [memberCount, setMemberCount] = useState(0);
const getGroupInfo = async () => {
let memberIDs = [];
let memberNames = [];
let memberImages = [];
let userGroupsRef = collection(db, "groups", groupID, "members");
onSnapshot(userGroupsRef, (querySnapshot) => {
querySnapshot.forEach((document) => {
memberIDs.push(document.id);
onSnapshot(doc(db, "users", document.id), (snapshot) => {
const one = snapshot.data();
const two = one.firstName;
const three = one.lastName;
const four = two + ' ' + three;
memberNames.push(four);
console.log(memberNames);
});
const pathReference = ref(storage, 'userProfileImage/' + document.id);
// Get the download URL
getDownloadURL(pathReference)
.then((url) => {
memberImages.push(url);
})
});
setMemberCount(memberIDs.length);
setMemIDLogs(memberIDs);
setMemNameLogs(memberNames);
setMemImagesLogs(memberImages);
})
and
const getGroupMembers = async () => {
let memberIDs = [];
let memberNames = [];
let paths = [];
let userGroupsRef = collection(db, "groups", groupID, "members");
onSnapshot(userGroupsRef, (querySnapshot) => {
querySnapshot.forEach((document) => {
memberIDs.push(document.id)
onSnapshot(doc(db, "users", document.id), (snapshot) => {
const one = snapshot.data();
const two = one.firstName;
const three = one.lastName;
const four = two + ' ' + three;
memberNames.push(four);
});
const pathReference = ref(storage, 'userProfileImage/' + document.id);
paths.push(pathReference);
})
setMemberCount(memberIDs.length);
setMemIDLogs(memberIDs);
setMemNameLogs(memberNames);
setImagePathReferences(paths);
})
return Promise.all(imagePathReference)
}
const getGroupPictures = async (file) => {
let downloadURL;
await getDownloadURL(file)
.then((url) => {
downloadURL = (url);
})
.catch((error) => {
// Handle any errors
if (error.code === "storage/object-not-found") {
downloadURL = ('');
}
});
return (downloadURL)
}
const getGroupInfo = async () => {
const references = await getGroupMembers();
console.log(references);
for (let i = 0; i < memberCount; i++) {
let file = references[i];
const references2 = await getGroupPictures(file);
memImagesLogs.push(references2);
}
};
A simple fix is to store the download URLs in an associative array, with the file as the key.
Something like this:
const downloadURLs = {}; // 👈
const getGroupInfo = async () => {
const references = await getGroupMembers();
console.log(references);
for (let i = 0; i < memberCount; i++) {
const file = references[i];
const downloadURL = await getGroupPictures(file);
downloadURLs[file] = downloadURL; // 👈
}
};
With that, the references array determines the order, while the downloadURLs object allows you to look up the download URL for each file.

I am trying to import an image on a pdf Canavas drawImage() but its Not Working

I am trying to import an image on a pdf using java script but am getting this error
:
TypeError: `image` must be of type `PDFImage`, but was actually of type `undefined
The image is in jpg format AND Here is the code for my java script file can anyone tell me what i am doing wrong:
const generatePDF = async (name,pic) => {
const { PDFDocument, rgb} = PDFLib;
const existingPdfBytes = await fetch("./cert.pdf").then((res) =>
res.arrayBuffer()
);
const exfont = await fetch("./Sanchez-Regular.ttf").then(res =>{
return res.arrayBuffer()
})
const pdfdoc = await PDFDocument.load(existingPdfBytes)
pdfdoc.registerFontkit(fontkit);
const myFont = await pdfdoc.embedFont(exfont);
const pages = pdfdoc.getPages();
const firstPg = pages[0]
firstPg.drawText(name,{
x:300,
y:310,
size:50,
font: myFont,
color: rgb(.2,0.84,0.67)
})
firstPg.drawImage(pic,100,100);
const uri = await pdfdoc.saveAsBase64({dataUri: true})
saveAs(uri,"Certificate.pdf");
};
const submitbtn = document.getElementById("submit1")
const inputval = document.getElementById("fname")
const inputcal = document.getElementById("logo1")
submitbtn.addEventListener("click",()=>{
const cal = inputcal.value;
const val = inputval.value;
generatePDF(val,cal) ;
})

Copy a document into a new collection in firestore using cloud function

Path 1 - Match_Creator/cricket/matchList;
Path 2 - Match_Creator/cricket/completedMatchList;
I have a collection called matchList (Path 1) In which i am having a doc called c434108.
Now I want to move this doc(c434108) to Path 2;
/* eslint-disable promise/catch-or-return */
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { db } = require("./db/index");
const createCompletedMatchListDoc = (request, response) => {
completedMatchDocsData();
};
function completedMatchDocsData() {
createNewCompletedMatchDocs()
}
function getOldCompletedMatchDocs(){
var completedMatchesRef = db
.collection("Match_Creator")
.doc("cricket")
.collection("matchList");
var completedMatchDocData;
var completedMatchDataArr = [];
return new Promise(resolve => {
let query = completedMatchesRef
.where("status", "==", "live")
.get()
.then(snapshot => {
// eslint-disable-next-line promise/always-return
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach(doc => {
completedMatchDocData = doc.data();
completedMatchDataArr.push(completedMatchDocData);
resolve(completedMatchDataArr);
});
console.log("sarang", completedMatchDataArr[2]);
})
.catch(err => {
console.log("Error getting documents", err);
});
});
}
const createNewCompletedMatchDocs = (async(change, context) => {
let completedMatchData = await getOldCompletedMatchDocs();
console.log('aman', completedMatchData[1]);
const newValue = change.after.data();
const previousValue = change.before.data();
const st1 =newValue.status;
const st2 = previousValue.status;
console.log('I am a log entry' + st1 + ' ' + st2);
var data = completedMatchData[0];
return db.collection('Match_Creator').doc('cricket').collection('completedMatchList').add(data)
.catch(error => {
console.log('Error writting document: ' + error);
return false;
});
})
module.exports = createCompletedMatchListDoc;
And After copy this doc(c434108) i want to delete this doc(c434108) from path 1.
And My index.js file is:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const storeMatchData = require("./liveScoring");
const createCompletedMatchListDoc = require("./completedMatchList");
var http = require("https");
module.exports = {
liveScoring: functions.https.onRequest(storeMatchData),
createCompletedMatchListDoc: functions.https.onRequest(
createCompletedMatchListDoc
)
};
I am able to solve my problem.
This is my completeMatchList.js file
/* eslint-disable promise/catch-or-return */
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { db } = require("./db/index");
const createCompletedMatchListDoc = (request, response) => {
completedMatchDocsData();
};
function completedMatchDocsData() {
setNewCompletedMatchDocs()
}
function getOldCompletedMatchDocs(){
var completedMatchesRef = db
.collection("Match_Creator")
.doc("cricket")
.collection("matchList");
var completedMatchDocData;
var completedMatchDataArr = [];
return new Promise(resolve => {
let query = completedMatchesRef
.where("status", "==", "live")
.get()
.then(snapshot => {
// eslint-disable-next-line promise/always-return
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach(doc => {
// completedMatchDocData = doc.data();
completedMatchDocData = {
docId: "",
docData: ""
}
completedMatchDocData.docId = doc.id;
completedMatchDocData.docData = doc.data();
completedMatchDataArr.push(completedMatchDocData);
resolve(completedMatchDataArr); // Here i am getting the data and pushing it in array
});
console.log("sarang", completedMatchDataArr);
})
.catch(err => {
console.log("Error getting documents", err);
});
});
}
const setNewCompletedMatchDocs = (async () => {
let getCompletedMatchData = await getOldCompletedMatchDocs();
// console.log("balram", getCompletedMatchData[0].docId);
let newCompletedMatchDocRef = db.collection("Match_Creator").doc("cricket").collection("completedMatchList").doc(getCompletedMatchData[0].docId);
return newCompletedMatchDocRef.set(getCompletedMatchData[0].docData); //set/copy the data to new path.
})
This is my main index.js file
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const storeMatchData = require("./liveScoring");
const createCompletedMatchListDoc = require("./completedMatchList");
const { db } = require("./db/index");
var http = require("https");
module.exports = {
liveScoring: functions.https.onRequest(storeMatchData),
createCompletedMatchListDoc: functions.https.onRequest(
createCompletedMatchListDoc
)
};
Now after copy document data to a new path i will delete the previous document. For deleting the document i have not written the function.
I'm not seeing anything that would allow you to move a document between collections(someone correct me if I'm wrong). You have to copy from the old collection to the new one and then remove the old one.
This is another post on StackOverflow that is running into this same issue and someone provided Java code on how to implement it.
EDIT: Updated link.
Hope this helps.

how to sign bitcoin psbt with ledger?

I'm trying to sign a Psbt transaction from bitcoinjs-lib following what I found here:
https://github.com/helperbit/helperbit-wallet/blob/master/app/components/dashboard.wallet/bitcoin.service/ledger.ts
I've checked that the compressed publicKey both from ledger, and the one from bitcoinjsLib returned the same value.
I could sign it with the bitcoinjs-lib ECPair, but when I tries to sign it using ledger, it is always invalid.
Can someone helps me point out where did I made a mistake?
These variables is already mentioned in the code below, but for clarity purpose:
- mnemonics:
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about
- previousTx:
02000000000101869362410c61a69ab9390b2167d08219662196e869626e8b0350f1a8e4075efb0100000017160014ef3fdddccdb6b53e6dd1f5a97299a6ba2e1c11c3ffffffff0240420f000000000017a914f748afee815f78f97672be5a9840056d8ed77f4887df9de6050000000017a9142ff4aa6ffa987335c7bdba58ef4cbfecbe9e49938702473044022061a01bf0fbac4650a9b3d035b3d9282255a5c6040aa1d04fd9b6b52ed9f4d20a022064e8e2739ef532e6b2cb461321dd20f5a5d63cf34da3056c428475d42c9aff870121025fb5240daab4cee5fa097eef475f3f2e004f7be702c421b6607d8afea1affa9b00000000
- paths:
["0'/0/0"]
- redeemScript: (non-multisig segwit)
00144328adace54072cd069abf108f97cf80420b212b
This is my minimum reproducible code I've got.
/* tslint:disable */
// #ts-check
require('regenerator-runtime');
const bip39 = require('bip39');
const { default: Transport } = require('#ledgerhq/hw-transport-node-hid');
const { default: AppBtc } = require('#ledgerhq/hw-app-btc');
const bitcoin = require('bitcoinjs-lib');
const mnemonics = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
const NETWORK = bitcoin.networks.regtest;
/**
* #param {string} pk
* #returns {string}
*/
function compressPublicKey(pk) {
const { publicKey } = bitcoin.ECPair.fromPublicKey(Buffer.from(pk, 'hex'));
return publicKey.toString('hex');
}
/** #returns {Promise<any>} */
async function appBtc() {
const transport = await Transport.create();
const btc = new AppBtc(transport);
return btc;
}
const signTransaction = async() => {
const ledger = await appBtc();
const paths = ["0'/0/0"];
const [ path ] = paths;
const previousTx = "02000000000101869362410c61a69ab9390b2167d08219662196e869626e8b0350f1a8e4075efb0100000017160014ef3fdddccdb6b53e6dd1f5a97299a6ba2e1c11c3ffffffff0240420f000000000017a914f748afee815f78f97672be5a9840056d8ed77f4887df9de6050000000017a9142ff4aa6ffa987335c7bdba58ef4cbfecbe9e49938702473044022061a01bf0fbac4650a9b3d035b3d9282255a5c6040aa1d04fd9b6b52ed9f4d20a022064e8e2739ef532e6b2cb461321dd20f5a5d63cf34da3056c428475d42c9aff870121025fb5240daab4cee5fa097eef475f3f2e004f7be702c421b6607d8afea1affa9b00000000"
const utxo = bitcoin.Transaction.fromHex(previousTx);
const segwit = utxo.hasWitnesses();
const txIndex = 0;
// ecpairs things.
const seed = await bip39.mnemonicToSeed(mnemonics);
const node = bitcoin.bip32.fromSeed(seed, NETWORK);
const ecPrivate = node.derivePath(path);
const ecPublic = bitcoin.ECPair.fromPublicKey(ecPrivate.publicKey, { network: NETWORK });
const p2wpkh = bitcoin.payments.p2wpkh({ pubkey: ecPublic.publicKey, network: NETWORK });
const p2sh = bitcoin.payments.p2sh({ redeem: p2wpkh, network: NETWORK });
const redeemScript = p2sh.redeem.output;
const fromLedger = await ledger.getWalletPublicKey(path, { format: 'p2sh' });
const ledgerPublicKey = compressPublicKey(fromLedger.publicKey);
const bitcoinJsPublicKey = ecPublic.publicKey.toString('hex');
console.log({ ledgerPublicKey, bitcoinJsPublicKey, address: p2sh.address, segwit, fromLedger, redeemScript: redeemScript.toString('hex') });
var tx1 = ledger.splitTransaction(previousTx, true);
const psbt = new bitcoin.Psbt({ network: NETWORK });
psbt.addInput({
hash: utxo.getId(),
index: txIndex,
nonWitnessUtxo: Buffer.from(previousTx, 'hex'),
redeemScript,
});
psbt.addOutput({
address: 'mgWUuj1J1N882jmqFxtDepEC73Rr22E9GU',
value: 5000,
});
psbt.setMaximumFeeRate(1000 * 1000 * 1000); // ignore maxFeeRate we're testnet anyway.
psbt.setVersion(2);
/** #type {string} */
// #ts-ignore
const newTx = psbt.__CACHE.__TX.toHex();
console.log({ newTx });
const splitNewTx = await ledger.splitTransaction(newTx, true);
const outputScriptHex = await ledger.serializeTransactionOutputs(splitNewTx).toString("hex");
const expectedOutscriptHex = '0188130000000000001976a9140ae1441568d0d293764a347b191025c51556cecd88ac';
// stolen from: https://github.com/LedgerHQ/ledgerjs/blob/master/packages/hw-app-btc/tests/Btc.test.js
console.log({ outputScriptHex, expectedOutscriptHex, eq: expectedOutscriptHex === outputScriptHex });
const inputs = [ [tx1, 0, p2sh.redeem.output.toString('hex') /** ??? */] ];
const ledgerSignatures = await ledger.signP2SHTransaction(
inputs,
paths,
outputScriptHex,
0, // lockTime,
undefined, // sigHashType = SIGHASH_ALL ???
utxo.hasWitnesses(),
2, // version??,
);
const signer = {
network: NETWORK,
publicKey: ecPrivate.publicKey,
/** #param {Buffer} $hash */
sign: ($hash) => {
const expectedSignature = ecPrivate.sign($hash); // just for comparison.
const [ ledgerSignature0 ] = ledgerSignatures;
const decodedLedgerSignature = bitcoin.script.signature.decode(Buffer.from(ledgerSignature0, 'hex'));
console.log({
$hash: $hash.toString('hex'),
expectedSignature: expectedSignature.toString('hex'),
actualSignature: decodedLedgerSignature.signature.toString('hex'),
});
// return signature;
return decodedLedgerSignature.signature;
},
};
psbt.signInput(0, signer);
const validated = psbt.validateSignaturesOfInput(0);
psbt.finalizeAllInputs();
const hex = psbt.extractTransaction().toHex();
console.log({ validated, hex });
};
if (process.argv[1] === __filename) {
signTransaction().catch(console.error)
}
Ooof, finally got it working.
My mistake was I was trying to sign a p2sh-p2ms, By following a reference on how to sign a p2sh-p2wsh-p2ms.
And, also, that missing last 2 bit (01), which I think represent SIGHASH_ALL caused an error when I try to decode the signature.
this is my finalized working example.
// #ts-check
require('regenerator-runtime');
const bip39 = require('bip39');
const { default: Transport } = require('#ledgerhq/hw-transport-node-hid');
const { default: AppBtc } = require('#ledgerhq/hw-app-btc');
const serializer = require('#ledgerhq/hw-app-btc/lib/serializeTransaction');
const bitcoin = require('bitcoinjs-lib');
const mnemonics = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
const NETWORK = bitcoin.networks.regtest;
const DEFAULT_LOCK_TIME = 0;
const SIGHASH_ALL = 1;
const PATHS = ["m/49'/1'/0'/0/0", "m/49'/1'/0'/0/1"];
async function appBtc() {
const transport = await Transport.create();
const btc = new AppBtc(transport);
return btc;
}
/**
* #param {string} pk
* #returns {string}
*/
function compressPublicKey(pk) {
const {
publicKey
} = bitcoin.ECPair.fromPublicKey(Buffer.from(pk, 'hex'));
return publicKey.toString('hex');
}
/**
* #param {AppBtc} ledger
* #param {bitcoin.Transaction} tx
*/
function splitTransaction(ledger, tx) {
return ledger.splitTransaction(tx.toHex(), tx.hasWitnesses());
}
const signTransaction = async() => {
const seed = await bip39.mnemonicToSeed(mnemonics);
const node = bitcoin.bip32.fromSeed(seed, NETWORK);
const signers = PATHS.map((p) => node.derivePath(p));
const publicKeys = signers.map((s) => s.publicKey);
const p2ms = bitcoin.payments.p2ms({ pubkeys: publicKeys, network: NETWORK, m: 1 });
const p2shP2ms = bitcoin.payments.p2sh({ redeem: p2ms, network: NETWORK });
const previousTx = '02000000000101588e8fc89afea9adb79de2650f0cdba762f7d0880c29a1f20e7b468f97da9f850100000017160014345766130a8f8e83aef8621122ca14fff88e6d51ffffffff0240420f000000000017a914a0546d83e5f8876045d7025a230d87bf69db893287df9de6050000000017a9142ff4aa6ffa987335c7bdba58ef4cbfecbe9e49938702483045022100c654271a891af98e46ca4d82ede8cccb0503a430e50745f959274294c98030750220331b455fed13ff4286f6db699eca06aa0c1c37c45c9f3aed3a77a3b0187ff4ac0121037ebcf3cf122678b9dc89b339017c5b76bee9fedd068c7401f4a8eb1d7e841c3a00000000';
const utxo = bitcoin.Transaction.fromHex(previousTx);
const txIndex = 0;
const destination = p2shP2ms;
const redeemScript = destination.redeem.output;
// const witnessScript = destination.redeem.redeem.output;
const ledgerRedeemScript = redeemScript;
// use witness script if the outgoing transaction was from a p2sh-p2wsh-p2ms instead of p2sh-p2ms
const fee = 1000;
/** #type {number} */
// #ts-ignore
const amount = utxo.outs[txIndex].value;
const withdrawAmount = amount - fee;
const psbt = new bitcoin.Psbt({ network: NETWORK });
const version = 1;
psbt.addInput({
hash: utxo.getId(),
index: txIndex,
nonWitnessUtxo: utxo.toBuffer(),
redeemScript,
});
psbt.addOutput({
address: '2MsK2NdiVEPCjBMFWbjFvQ39mxWPMopp5vp',
value: withdrawAmount
});
psbt.setVersion(version);
/** #type {bitcoin.Transaction} */
// #ts-ignore
const newTx = psbt.__CACHE.__TX;
const ledger = await appBtc();
const inLedgerTx = splitTransaction(ledger, utxo);
const outLedgerTx = splitTransaction(ledger, newTx);
const outputScriptHex = await serializer.serializeTransactionOutputs(outLedgerTx).toString('hex');
/** #param {string} path */
const signer = (path) => {
const ecPrivate = node.derivePath(path);
// actually only publicKey is needed, albeit ledger give an uncompressed one.
// const { publicKey: uncompressedPublicKey } = await ledger.getWalletPublicKey(path);
// const publicKey = compressPublicKey(publicKey);
return {
network: NETWORK,
publicKey: ecPrivate.publicKey,
/** #param {Buffer} $hash */
sign: async ($hash) => {
const ledgerTxSignatures = await ledger.signP2SHTransaction({
inputs: [[inLedgerTx, txIndex, ledgerRedeemScript.toString('hex')]],
associatedKeysets: [ path ],
outputScriptHex,
lockTime: DEFAULT_LOCK_TIME,
segwit: newTx.hasWitnesses(),
transactionVersion: version,
sigHashType: SIGHASH_ALL,
});
const [ ledgerSignature ] = ledgerTxSignatures;
const expectedSignature = ecPrivate.sign($hash);
const finalSignature = (() => {
if (newTx.hasWitnesses()) {
return Buffer.from(ledgerSignature, 'hex');
};
return Buffer.concat([
ledgerSignature,
Buffer.from('01', 'hex'), // SIGHASH_ALL
]);
})();
console.log({
expectedSignature: expectedSignature.toString('hex'),
finalSignature: finalSignature.toString('hex'),
});
const { signature } = bitcoin.script.signature.decode(finalSignature);
return signature;
},
};
}
await psbt.signInputAsync(0, signer(PATHS[0]));
const validate = await psbt.validateSignaturesOfAllInputs();
await psbt.finalizeAllInputs();
const hex = psbt.extractTransaction().toHex();
console.log({ validate, hex });
};
if (process.argv[1] === __filename) {
signTransaction().catch(console.error)
}
My guess is you have a space in the string passed to toByteArray function. This function doesn't trim input. Also doesn't check if input's length is even.

Categories