Deno run is not working properly also drun - deno

After created an index.ts and wrote a simple code for listening to port 3000 and printing hello world on the body, I'm also not able to run or get the output from deno's drun module.
import { Application, Router } from "https://deno.land/x/denotrain#v0.5.0/mod.ts";
const app = new Application();
const router = new Router();
// Middleware
app.use((ctx) => {
ctx.cookies["user.session"] = "qwertz";
ctx.cookies["a"] = "123";
ctx.cookies["b"] = "456";
delete ctx.cookies["user.session"];
return;
});
router.get("/", (ctx) => {
return new Promise((resolve) => resolve("This is the admin interface!"));
});
router.get("/edit", async (ctx) => {
return "This is an edit mode!";
});
app.get("/", (ctx) => {
return {"hello": "world"};
});
app.use("/admin", router);
app.get("/:id", (ctx) => {
// Use url parameters
return "Hello World with ID: " + ctx.req.params.id
});
return ctx.req.body;
});
await app.run()

Development Environment:- Windows 10
The problem seems to be the address 0.0.0.0 is specific to mac only.Windows Doesn't use 0.0.0.0 address.
After going to localhost:3000 / 127.0.0.1:3000. I was able to get the output.I think maybe Windows redirects the 0.0.0.0 to localhost. Anyway it solved my problem!

I am on windows. I faced with the same problem. Then,
const app = new Application({hostname:"127.0.0.1"});
I created the app in typescript giving parameter hostname like above.
And run deno like this:
deno run --allow-net=127.0.0.1 index.ts
it worked.

Run your server with the following command:
drun watch --entryPoint=./server.ts --runtimeOptions=--allow-net
In any case most Deno tools for watching changes are still bugged, I recommend to use nodemon, with --exec flag
nodemon --exec deno run --allow-net server.ts
For convenience you can use nodemon.json with the following content:
{
"execMap": {
"js": "deno run --allow-net",
"ts": "deno run --allow-net"
},
"ext": "js,json,ts"
}
And now just use: nodemon server.ts

It seems that you have an error in your code snippet, with the last
return ctx.req.body;
});
If you fix that and use the last deno (v1.0.1) and drun(v1.1.0) versions it should works with the following command:
drun --entryPoint=index.ts --runtimeOptions=--allow-net

Related

Identifier 'module' has already been declared - amplify and nuxt 3

I am getting an error in nuxt3 then setting up this amplify plugin. I am trying to add auth to nuxt3 via plugins
plugins/amplify.js
import Amplify, {withSSRContext} from 'aws-amplify';
export default defineNuxtPlugin((ctx) => {
const awsConfig = {
Auth: {
region: "ap-south-1",
userPoolId: "ap-south-1_#########",
userPoolWebClientId: "#####################",
authenticationFlowType: "USER_SRP_AUTH",
},
};
Amplify.configure({ ...awsConfig, ssr: true });
if (process.server) {
const { Auth } = withSSRContext(ctx.req);
return {
provide: {
auth: Auth,
},
};
}
return {
provide: {
auth: Auth,
},
};
}
[nuxt] [request error] Identifier 'module' has already been declared
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
at async link (internal/modules/esm/module_job.js:67:21)
Does anyone know what's going on?
Been facing this myself... I don't think its a nuxt problem but rather Vite.
I gave up on running the app on dev mode and just resorted to building the app and launching it. Also, in order to use aws-amplify with vite you need to apply some workarounds:
https://ui.docs.amplify.aws/vue/getting-started/troubleshooting
For the window statement (which only makes sense on the browser) you'll need to wrap that with an if statement. Added this to my plugin file
if (process.client) {
window.global = window;
var exports = {};
}
This will let you build the project and run it with npm run build . Far from ideal but unless someone knows how to fix that issue with dev in vite...
BTW, you can also just switch to webpack builder on nuxt settings and the issue goes away.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
builder: "webpack"
});
I think this might be a problem with auto imports of nuxt.
I added a ~/composables/useBucket.ts file which I used in ~/api. Same error started popping up the next day. After I moved ~/composables/useBucket.ts to ~/composablesServer/useBucket.ts issue disappeared.

Firebase Functions ENOENT: no such file or directory, open 'HttpsErrorImpl'

I'm fighting with this issue for over 3 days. I have no idea what is happening.
Firebase Functions throws error only when I try to use Emulator. I try to execute this function in useEffect hook. Again, when I call deployed Cloud Functions everything seems fine, unfortunately in case of using Emulator things don't want to go so well.
const resolvePromise = async () => {
functions.useEmulator("https://0.0.0.0:5001");
const query = functions.httpsCallable("helloWorld");
query()
.then((result) => console.log(result))
.catch((err) => console.log(err));
};
I receive this useless (for me) error.
Error: ENOENT: no such file or directory, open 'HttpsErrorImpl#http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at getCodeFrame (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:1296:18)
at Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:1367:24
at Generator.next (<anonymous>)
at asyncGeneratorStep (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:146:24)
at _next (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:168:9)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
internal
at HttpsErrorImpl#http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197178:29 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197273:29 in _errorForResponse
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197751:39 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170357:26 in step
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170287:21 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170241:31 in fulfilled
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31526:15 in tryCallOne
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31627:26 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31955:16 in _callTimer
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31994:16 in _callImmediatesPass
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:32211:32 in callImmediates
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3457:34 in __callImmediates
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3236:33 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3440:14 in __guard
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3235:20 in flushedQueue
This is all the text which I can see after visiting
http://192.168.0.104:19000/index.bundle -- https://pastebin.com/ggsCMN0W
http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false -- https://pastebin.com/LSeufs8H
It don't make any sense for me. At second address it seems like it's correlated to metro dependency so I updated it, it didn't work.
Any ideas? Thanks in advance :D
Edit 1: All errors are logged at client site, it seems like client can't even call emulator.
Edit 2:
I tried to update entire firebase to v.9 aswell as Expo to 44 SKD with react-native to 0.64.3
This is how my Request function looks now:
const requestApi = () => {
const functions = getFunctions(app);
connectFunctionsEmulator(functions, "127.0.0.1", 5001);
const helloWorld = httpsCallable(functions, "helloWorld");
helloWorld()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message, error.code, error.details);
});
};
I receive only this from catch block :(
internal functions/internal undefined
I also receive warning about Timer after executing that function
Setting a timer for a long period of time, i.e. multiple minutes, is a
performance and correctness issue on Android as it keeps the timer
module awake, and timers can only be called when the app is in the
foreground. See https://github.com/facebook/react-native/issues/12981
for more info. (Saw setTimeout with duration 70000ms)
It don't work only when I try to use Emulator
Couple of potential issues here:
Assuming you're using the latest version of Firebase, functions is actually a method: firebase.functions().useEmulator("localhost", 5001); - Note the () after functions. See docs for more info.
Maybe you've already done this, but have you made sure that the functions emulator is actually running and connectable on port 5001)? Could be useful to test it via Postman or similar.
Make sure you're using the correct IP address for the functions emulator given your setup. 0.0.0.0 probably doesn't map where you want it to... assuming the app is running locally and the functions emulator is too, try 127.0.0.1 or "localhost" ... this answer has more options to troubleshoot.
I am not sure if it is your case, but I had a function:
exports.findUserInAuth = functions.https.onCall((data, context) => {
let field = data.field;
let value = data.value;
if (!field || !value) {
return false;
}
if (field === "email") {
return admin.auth().getUserByEmail(value);
}
});
This one returns a promise, I had to change it to wait for the result before doing a return and problem solved...
exports.findUserInAuth = functions.https.onCall((data, context) => {
let field = data.field;
let value = data.value;
if (!field || !value) {
return false;
}
if (field === "email") {
admin.auth().getUserByEmail(value).then((result) => {
return result;
})
.catch((error) => {
if (error.code === "auth/user-not-found") {
return "Email or Password is incorrect";
}
return `${error.code} ${error.message}`;
});
}
return false;
});
Ok, so after almost a week of fighting with this sh!t.
When you use Expo Go like me. You should copy the host address on which you are emulating your app, and use the same address you emulate your functions (or other tools).
app.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"emulators": {
"functions": {
"host": "192.168.0.104",
"port": 5001
}
}
}
and final code of requestApi function
const requestApi = async () => {
const functions = firebase.functions()
functions.useEmulator("192.168.0.104", 5001); <--- ADDRESS!!!
const helloWorld = functions.httpsCallable("helloWorld");
helloWorld()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message, error.code, error.details);
});
};

When deploying contract using hardhat to Mumbai (Polygon) the address already exists

Contract deploys to address 0x47c5e40890bcE4a473A49D7501808b9633F29782
It looks like many other contracts were deployed to the same address by other people.
Should the address of the contract not be unique or is it deterministically generated or cached somehow by hardhat?
Why would other people have deployed to the same address?
I am wondering if this is some bug with Polygon/Mumbai testnet
const { ethers } = require("hardhat");
async function main() {
const SuperMarioWorld = await ethers.getContractFactory("Rilu");
const superMarioWorld = await SuperMarioWorld.deploy("Rilu", "RILU");
await superMarioWorld.deployed();
console.log("Success contract was deployed to: ", superMarioWorld.address)
await superMarioWorld.mint("https://ipfs.io/ipfs/QmZkUCDt5CVRWQjLDyRS4c8kU6UxRNdpsjMf6vomDcd7ep")
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Hardhat
module.exports = {
solidity: '0.8.4',
networks: {
mumbai: {
url: process.env.MUMBAI_RPC,
accounts: [process.env.PRIVATE_KEY],
},
},
};
.env file (no problem with sharing the private key, just one I got from vanity-eth.tk and used for testing)
PRIVATE_KEY=84874e85685c95440e51d5edacf767f952f596cca6fd3da19b90035a20f57e37
MUMBAI_RPC=https://rpc-mumbai.maticvigil.com
Output
~/g/s/b/r/nft ❯❯❯ npx hardhat run scripts/deploy.js --network mumbai ✘ 1
Compiling 12 files with 0.8.4
Compilation finished successfully
Success contract was deployed to: 0x47c5e40890bcE4a473A49D7501808b9633F29782

Setting up HTTPS on Deno , with self signed certificate?

I was setting up a Deno server to handle HTTPS request, I used self signed certificates to do the job.
Used below code for this:
import { serveTLS } from "https://deno.land/std/http/server.ts";
const body = new TextEncoder().encode("Hello HTTPS");
const options = {
hostname: "localhost",
port: 443,
certFile: "./path/to/localhost.crt",
keyFile: "./path/to/localhost.key",
};
// Top-level await supported
for await (const req of serveTLS(options)) {
req.respond({ body });
}
I ran this code as: deno --allow-net --allow-read app.ts
I get following error:
ERROR RS - rustls::session:571 - TLS alert received: Message {
typ: Alert,
version: TLSv1_3,
payload: Alert(
AlertMessagePayload {
level: Fatal,
description: BadCertificate,
},
),
}
error: Uncaught InvalidData: received fatal alert: BadCertificate
► $deno$/errors.ts:57:13
at InvalidData ($deno$/errors.ts:135:5)
at constructError ($deno$/errors.ts:57:13)
at unwrapResponse ($deno$/dispatch_json.ts:41:12)
at sendAsync ($deno$/dispatch_json.ts:96:10)
Is it possible to use self signed certificates with Deno ?
What went wrong and how to fix it ?
It was a problem with my certificate files, strangly the same certificates were working with nodejs.
I created local certificates and key than using this mkcert, then it worked!
If you're on MacOS, the best way to fix this is to instruct Deno to look at the system as the CA store.
Run this, then try again to see if you still get a warning/error:
export DENO_TLS_CA_STORE=system
You probably also want this in your .bash_profile as well.

Meteor npm run script on server restart

Is there a way to run an npm script on every Meteor server restart?
I tried the postinstall hook but it runs only at the first local application start.
I assume, that there must be way, because the restart triggers several building processes and some of them must be "hookable".
I was first thinking of using build plugins, but it seems, that they move a lot of config away from my package.json then.
Anyone knows something about this?
You can run your npm script within your Meteor.startup() code on the server side. The following example which should be located under the /server folder might help.
import { exec } from 'child_process';
Meteor.startup(() => {
async function sh(cmd) {
return new Promise(function (resolve, reject) {
exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve({ stdout, stderr });
}
});
});
}
async function excScript() {
let { stdout } = await sh('npm -ls'); // runs "npm -ls"
for (let line of stdout.split('\n')) {
console.log(`npm -ls: ${line}`);
}
}
excScript();
}

Resources