Why Sentry throws “Invalid token” (http status: 401) error for a valid token?

I’ve got a next.js application that connected to sentry and I’m confident about the token, But when I tried to run npm run build in my app to get output I faced Invalid token (http status: 401) error.

Note that npm run dev has no problem!

Here’s my .env.local :

NEXT_PUBLIC_API_BASE_URL="something's here" 
NEXT_LOGGING_API_URL="XXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 
SENTRY_AUTH_TOKEN="XXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 
SENTRY_LOG_LEVEL=debug 

and I also have withSentryConfig in my next.config.js :

withSentryConfig(module.exports, { silent: true }, { hideSourcemaps: true })

I ran npm run build and I faced this error:

error: API request failed
  caused by: sentry reported an error: Invalid token (http status: 401)
  DEBUG   2024-07-20 18:03:44.635547900 +03:30 skipping update nagger because session is not attended

thunderbird, how to javascript in oauth2 dialog but not mail views?

We’d like to keep thunderbird secure by not accepting cookies and not running javascript when viewing emails, has it’s always been.

However, we’ll have to enable them for oauth2’s flow’s dialog (the ms recent push forcing us).

Now, I know, it’s a dialog that shows only once every 365 days when the refresh token is expired. So I could turn js+cookies off until 1 year later, to refresh the refresh token.

The problem is not mine, it’s one for clueless users I support of course.
How could I simplify turning both js+cookies, or better yet, have them enabled ONLY while in a oauth2 flow context?

I’m thinking a couple (on vs off) shell script to change the user.js in the thunderbird profile. But that’s still pretty reactive. The user will have to recall the js+cookie errors meaning, run desktop icons and not forget to revert.

(please don’t suggest to file a RFE to mozilla – I will if it’s not there already).

I’ll probably block thunderbird from access the non pop/imap/smtp ports, but that doesn’t help evil scripts to run locally.

Unable to Sign In with Keycloak using NextAuth in Next.js Application [next-auth][error][SIGNIN_OAUTH_ERROR]

I’m trying to set up authentication for my Next.js application using NextAuth and Keycloak. Despite following the documentation, I’m encountering an issue when attempting to sign in with Keycloak.

My Setup

Next.js: 13.x, NextAuth: 4.x, Keycloak: 25.x

pages/api/auth/[…nextauth].js

// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import KeycloakProvider from "next-auth/providers/keycloak";

export default NextAuth({
  providers: [
    KeycloakProvider({
      clientId: process.env.KEYCLOAK_CLIENT_ID,
      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET,
      issuer: process.env.KEYCLOAK_ISSUER,
    }),
  ],
  session: {
    jwt: true,
  },
  debug: true, // Enable debug mode
  callbacks: {
    async jwt({ token, account, user }) {
      if (account) {
        token.accessToken = account.access_token;
        token.user = token.user;
      }
      return token;
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken;
      session.user = token.user;
      return session;
    },
  },
});

.env

KEYCLOAK_CLIENT_ID=your-client-id
KEYCLOAK_CLIENT_SECRET=your-client-secret
KEYCLOAK_ISSUER=http://localhost:8080/realms/myrealm

Keycloak Configuration:

I have configured my Keycloak client with the following settings:

Client ID: your-client-id
Client Protocol: openid-connect
Access Type: confidential
Root URL: http://localhost:3000
Valid Redirect URIs: http://localhost:3000/api/auth/callback/keycloak
Web Origins: http://localhost:3000

In console I see

[next-auth][error][SIGNIN_OAUTH_ERROR]
https://next-auth.js.org/errors#signin_oauth_error Unable to find matching target resource method (For more on this error consult the server log at the debug level.)

What could be causing the SIGNIN_OAUTH_ERROR with the message “Unable to find matching target resource method”? How can I resolve this issue to successfully sign in with Keycloak?

Please let me know if any additional details are required or if there are specific configurations I need to double-check. Any help would be greatly appreciated!

Thanksenter image description here

Trouble Intercepting CAPTCHA Parameters Using Selenium and JavaScript for 2Captcha

I am trying to intercept CAPTCHA parameters from a webpage using Selenium and JavaScript. My goal is to use the 2Captcha service to solve the turnstile CAPTCHA on ahrefs. The issue I’m facing is that the parameters are not being intercepted correctly.

Here is my setup:

Python: 3.x
Selenium: seleniumbase
Browser: Chrome (headless mode)
CAPTCHA solving service: 2Captcha

Code:

import json
import re
import requests
from seleniumbase import Driver
from selenium.webdriver.common.by import By
import time

proxy = "xxxxxx:[email protected]:xxxx"  # YOUR_2CAPTCHA_PROXY
my_key = "KEY_HERE_API"

# Setting up an updated UserAgent
agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"

# Configuring the web driver to work in headless mode
driver = Driver(uc=True, log_cdp=True, headless=True, no_sandbox=True, agent=agent, proxy=False)

# URL of the website protected by the Turnstile CAPTCHA
url = "https://ahrefs.com/es/backlink-checker?input=google.com"
driver.get(url)
driver.refresh()
time.sleep(10)  # Increased wait time to ensure the page and Turnstile CAPTCHA are fully loaded

# Function to intercept CAPTCHA parameters using JavaScript
def intercept(driver):
    print("Executing JavaScript to intercept CAPTCHA parameters...")
    driver.execute_script("""
    console.clear = () => console.log('Console was cleared')
    console.log('Checking for Turnstile...')
    const i = setInterval(()=>{
        if (window.turnstile) {
            console.log('Turnstile loaded')
            clearInterval(i)
            window.turnstile.render = (a, b) => {
                console.log('Overriding render function')
                let params = {
                    sitekey: b.sitekey,
                    pageurl: window.location.href,
                    data: b.cData,
                    pagedata: b.chlPageData,
                    action: b.action,
                    userAgent: navigator.userAgent,
                    json: 1
                }
                console.log('intercepted-params:' + JSON.stringify(params))
                window.cfCallback = b.callback
                console.log('Render function overridden')
                return
            }
        }
    }, 50)
    """)
    time.sleep(10)  # Increased sleep time to ensure parameters are captured
    print("Retrieving browser logs for intercepted parameters...")
    logs = driver.get_log("browser")
    for log in logs:
        if log['level'] == 'INFO':
            print("Log entry:", log['message'])
            if "intercepted-params:" in log["message"]:
                log_entry = log["message"].encode('utf-8').decode('unicode_escape')
                match = re.search(r'"intercepted-params:({.*?})"', log_entry)
                if match:
                    json_string = match.group(1)
                    params = json.loads(json_string)
                    return params
    return None

params = intercept(driver)

if params is None:
    print("Failed to intercept CAPTCHA parameters.")
    driver.close()
    driver.quit()
    exit(0)

print("Intercepted CAPTCHA parameters:", params)

data0 = {
    "key": my_key,
    "method": "turnstile",
    "sitekey": params["sitekey"],
    "action": params["action"],
    "data": params["data"],
    "pagedata": params["pagedata"],
    "useragent": params["userAgent"],
    "json": 1,
    "pageurl": params["pageurl"],
}
response = requests.post("https://2captcha.com/in.php", data=data0)
print("Request sent", response.text)
s = response.json()["request"]

while True:
    solu = requests.get(f"https://2captcha.com/res.php?key={my_key}&action=get&json=1&id={s}").json()
    if solu["request"] == "CAPCHA_NOT_READY":
        print(solu["request"])
        time.sleep(8)
    elif "ERROR" in solu["request"]:
        print(solu["request"])
        driver.close()
        driver.quit()
        exit(0)
    else:
        break

for key, value in solu.items():
    print(key, ": ", value)

solu = solu['request']
driver.execute_script(f"cfCallback('{solu}');")
time.sleep(5)

Logs and Observations:

The script prints “Checking for Turnstile…” and “Turnstile loaded,” indicating that the Turnstile library is loaded.
However, the script fails to intercept the CAPTCHA parameters and prints “Failed to intercept CAPTCHA parameters.”

Questions:

Why is the render function override not capturing the CAPTCHA parameters?
Is there a better way to intercept these parameters using Selenium and JavaScript?
Any other suggestions to improve the interception process?

Any help would be greatly appreciated! Thank you.

How does browser control + f search works? If I added a search bar on my page and want to apply same logic to get highlighted words which are written [closed]

When I enter “Control + F” on a browser then there is a search bar in the bottom in which if we search any word, then all the words related to that are highlighted. So I have added a search bar which is currently static on my angular application. but I want to achieve same behaviour of highlighting words which are written in the search bar.

.highlight { background-color: yellow; }

Rafraichir mon composant react

I would like the component to refresh when clicking on the ‘faHeart’ icon, I wanted to use the useState as on another component but on this one it does not work.

Fetch


function Hastags({}) {
  const tweets = useSelector((state) => state.tweet.value);
  const user = useSelector((state) => state.user.value);

  //console.log("tweet is ", tweets);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [refresh, setRefresh] = useState(false);

 

  const handleLikedTweet = (id) => {
    fetch(`http://localhost:3000/tweet/incrementLike/${id}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token: user.token }),
    }).then((response) => {
      setRefresh(!refresh);
      console.log("Response is ", response);
    });
  };


      <Modal
        isOpen={isModalOpen}
        onRequestClose={closeModal}
        contentLabel="Hashtag Messages"
        className={styles.modal}
        overlayClassName={styles.overlay}
      >
        <FontAwesomeIcon onClick={closeModal} icon={faXmark} size="lg" />
        <h2>Messages with #{currentHashtag} :</h2>
        <div className={styles.messages}>
          {filteredMessages.map((message, i) => (
            <div className={styles.containerHash} key={i}>
              <div className={styles.profil}>
                <img
                  className={styles.avatar}
                  src={`https://robohash.org/${user.username}.png`}
                  alt="Avatar"
                />
                <p className={styles.info}>
                  {" "}
                  <span style={{ fontSize: "17px" }}>
                    {message.user.firstName}
                  </span>{" "}
                  <span style={{ fontSize: "12px", color: "lightgray" }}>
                    @{message.user.userName}
                  </span>
                </p>
              </div>
              <span style={{ paddingLeft: "70px" }}>{message.message}</span>
              <FontAwesomeIcon
                onClick={() => handleLikedTweet(tweets._id)}
                icon={faHeart}
                className={styles.icon}
                color={message.likeBy.includes(user.token) ? "red" : "white"}
              />
            </div>
          ))}
        </div>
      </Modal>
   

“Error: Module not found: Can’t resolve ‘crypto’ in Expo SDK 50”

I’m encountering an issue after upgrading to Expo SDK 50. When I try to run my project, I get the following error:

Module not found: Can't resolve 'crypto'
   7 |   const cryptoObject =
   8 |     typeof crypto === 'undefined' || typeof crypto.randomUUID === 'undefined'
>  9 |       ? require('crypto')
     |        ^
  10 |       : crypto;
  11 |
  12 |   if (!cryptoObject?.randomUUID) {

It seems like the module ‘crypto’ is not being found or resolved properly. Here is the relevant code snippet:

import v35 from './lib/v35';
import { Uuidv5Namespace } from './uuid.types';
function uuidv4() {
    // Crypto needs to be required when run in Node.js environment.
    const cryptoObject = typeof crypto === 'undefined' || typeof crypto.randomUUID === 'undefined'
        ? require('crypto')
        : crypto;
    if (!cryptoObject?.randomUUID) {
        throw Error("The browser doesn't support `crypto.randomUUID` function");
    }
    return cryptoObject.randomUUID();
}
const uuid = {
    v4: uuidv4,
    v5: v35('v5', 0x50, sha1),
    namespace: Uuidv5Namespace,
};
export default uuid;
//# sourceMappingURL=uuid.web.js.map

I’ve tried searching for a solution but haven’t found anything that works. Has anyone faced a similar issue or knows how to resolve this?

Thanks in advance for your help!

Gemini API import issues in Javascript

I am new to JS and APIs in general. I was trying to create a chatbot using gemini’s api and I followed the basic template that is on gemini’s documentation i.e

const { GoogleGenerativeAI } = require("@google/generative-ai");

This is causing a few issues. First of all because of using this package, the website itself is not loading. Secondly, a function in my JS file considers it is not being used even though it is and this only happens when I use the line of code I provided above.

here’s the entire js file if it helps

console.log("Start");
const chatInput = document.querySelector("#chat-input");
const sendButton = document.querySelector("#send-btn");
const chatContainer = document.querySelector(".chat-container");
const themeButton = document.querySelector("#theme-btn");
const deleteButton = document.querySelector("#delete-btn");
const { GoogleGenerativeAI } = require("@google/generative-ai");
let userText = null;
let answer = null;
const genAI = new GoogleGenerativeAI("API-KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

const loadDataFromLocalstorage = () => {
    console.log("loadDataFromLocalstorage");
  // Load saved chats and theme from local storage and apply/add on the page
  const themeColor = localStorage.getItem("themeColor");

  document.body.classList.toggle("light-mode", themeColor === "light_mode");
  themeButton.innerText = document.body.classList.contains("light-mode") ? "dark_mode" : "light_mode";

  const defaultText = `<div class="default-text">
                          <h1>ChatGPT Clone</h1>
                          <p>Start a conversation and explore the power of AI.<br> Your chat history will be displayed here.</p>
                      </div>`

  chatContainer.innerHTML = localStorage.getItem("all-chats") || defaultText;
  chatContainer.scrollTo(0, chatContainer.scrollHeight); // Scroll to bottom of the chat container
}

const createChatElement = (content, className) => {
    console.log("createChatElement");
    // Create new div and apply chat, specified class and set html content of div
    const chatDiv = document.createElement("div");
    chatDiv.classList.add("chat", className);
    chatDiv.innerHTML = content;
    return chatDiv; // Return the created chat div
}

const copyResponse = (copyBtn) => 
{
    console.log("copyResponse");
    // Copy the text content of the response to the clipboard
    const reponseTextElement = copyBtn.parentElement.querySelector("p");
    navigator.clipboard.writeText(reponseTextElement.textContent);
    copyBtn.textContent = "done";
    setTimeout(() => copyBtn.textContent = "content_copy", 1000);
}


const showTypingAnimation = () => {
    console.log("showTypingAnimation");
    // Display the typing animation and call the getChatResponse function
    const html = `<div class="chat-content">
                    <div class="chat-details">
                        <img src="images/chatbot.jpg" alt="chatbot-img">
                        <div class="typing-animation">
                            <div class="typing-dot" style="--delay: 0.2s"></div>
                            <div class="typing-dot" style="--delay: 0.3s"></div>
                            <div class="typing-dot" style="--delay: 0.4s"></div>
                        </div>
                    </div>
                    <span onclick="copyResponse(this)" class="material-symbols-rounded">content_copy</span>
                </div>`;
    // Create an incoming chat div with typing animation and append it to chat container
    const incomingChatDiv = createChatElement(html, "incoming");
    chatContainer.appendChild(incomingChatDiv);
    chatContainer.scrollTo(0, chatContainer.scrollHeight);
    getChatResponse(incomingChatDiv);
}

async function res(prompt)
{
    console.log("res");
    const result = await model.generateContent(prompt);
    const response = await result.response;
    let ans = response.text();
    return ans;
}

const getChatResponse = async (incomingChatDiv) => 
{
    console.log("getChatResponse");
    const pElement = document.createElement("p");
    
    const prefix = "Give me advice ";
    const question = userText;
    const suffix = ". keep it limited to 200 words while being specific to the problem";
    const prompt = prefix+question+suffix;
    
    // Send POST request to API, get response and set the reponse as paragraph element text
    try 
    {
        (async () => {
            answer = await res(prompt);
        })();
        pElement.textContent = answer.trim();
    } 
    catch (error) { // Add error class to the paragraph element and set error text
        pElement.classList.add("error");
        pElement.textContent = "Oops! Something went wrong while retrieving the response. Please try again.";
    }

    // Remove the typing animation, append the paragraph element and save the chats to local storage
    incomingChatDiv.querySelector(".typing-animation").remove();
    incomingChatDiv.querySelector(".chat-details").appendChild(pElement);
    localStorage.setItem("all-chats", chatContainer.innerHTML);
    chatContainer.scrollTo(0, chatContainer.scrollHeight);
}

const handleOutgoingChat = () => {
    console.log("handleOutgoingChat");
    userText = chatInput.value.trim(); // Get chatInput value and remove extra spaces
    if(!userText) return; // If chatInput is empty return from here

    // Clear the input field and reset its height
    chatInput.value = "";
    chatInput.style.height = `${initialInputHeight}px`;

    const html = `<div class="chat-content">
                    <div class="chat-details">
                        <img src="images/user.jpg" alt="user-img">
                        <p>${userText}</p>
                    </div>
                </div>`;

    // Create an outgoing chat div with user's message and append it to chat container
    const outgoingChatDiv = createChatElement(html, "outgoing");
    chatContainer.querySelector(".default-text")?.remove();
    chatContainer.appendChild(outgoingChatDiv);
    chatContainer.scrollTo(0, chatContainer.scrollHeight);
    setTimeout(showTypingAnimation, 500);
}

deleteButton.addEventListener("click", () => {
    console.log("addEventListenerdel");
    // Remove the chats from local storage and call loadDataFromLocalstorage function
    if(confirm("Are you sure you want to delete all the chats?")) {
        localStorage.removeItem("all-chats");
        loadDataFromLocalstorage();
    }
});

themeButton.addEventListener("click", () => {
    console.log("addEventListenermode");
    // Toggle body's class for the theme mode and save the updated theme to the local storage 
    document.body.classList.toggle("light-mode");
    localStorage.setItem("themeColor", themeButton.innerText);
    themeButton.innerText = document.body.classList.contains("light-mode") ? "dark_mode" : "light_mode";
});

const initialInputHeight = chatInput.scrollHeight;

chatInput.addEventListener("input", () => {  
    console.log("addEventListenerinput");
    // Adjust the height of the input field dynamically based on its content
    chatInput.style.height =  `${initialInputHeight}px`;
    chatInput.style.height = `${chatInput.scrollHeight}px`;
});

chatInput.addEventListener("keydown", (e) => {
    console.log("addEventListenerkeydown");
    // If the Enter key is pressed without Shift and the window width is larger 
    // than 800 pixels, handle the outgoing chat
    if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) {
        e.preventDefault();
        handleOutgoingChat();
    }
});

loadDataFromLocalstorage();
sendButton.addEventListener("click", handleOutgoingChat);


When I hover above the require line, I get this message
“File is a CommonJS module; it may be converted to an ES module.ts(80001)”

but even if I change it to
‘import { GoogleGenerativeAI } from “@google/generative-ai”;’

It still doesn’t help. I even tried using this api in another js file and importing that file into my main js file thinking that would help but it didn’t. I have looked alot online and can’t figure out.

card slide animation not occuring on both sides

I wanted to make an animated cared slider similar to the image below for my website:
https://i.ytimg.com/vi/Xh-wIMqohD0/maxresdefault.jpg
Everything is perfectly fine and functioning properly. Except that the cards are not on both the sides. It’s only appearing in one side.

I was expecting it to appear on both sides however, It only appears on one side and I can’t seem to figure out where the probleml is in the code.
Here’s the HTML, CSS and Javascript code respectively:
HTML:

<div class="slider">
    <div class="item">
        <h1>card7</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <div class="item">
        <h1>Card6</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <div class="item">
        <h1>card5</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <div class="item">
        <h1>Card1</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <div class="item">
        <h1>card2</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <div class="item">
        <h1>card3</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <div class="item">
        <h1>card4</h1>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi impedit quibusdam qui. Adipisci fugit perspiciatis corporis culpa, repellat illum autem nobis earum id modi beatae cupiditate obcaecati praesentium vitae magnam aspernatur officia perferendis, maiores a alias hic quae dolores. Dicta?
    </div>
    <button id="next">></button>
    <button id="prev"><</button>
</div>

CSS:

.slider{
  position: relative;
  margin-top: 100px;
  width: 100%;
  height: 370px;
  overflow: hidden;
}

.item{
  position: absolute;
  width: 200px;
  height: 320px;
  text-align: justify;
  background-color: #5d5d5d;
  /*backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);*/
  border-radius: 8px;
  padding: 20px;
  transition: 0.5s;
  left: calc(50% - 110px);
  top: 0;
}

#next, #prev{
  position: absolute;
  top: 10%;
  color: #fff;
  background-color: transparent;
  border: none;
  font-size: 50px;
  font-family: 'cabinet Grotesk', sans-serif;
  font-weight: bold;
  left: 30px;
}

#next{
  left: unset;
  right: 30px;

}

Javascript:

let items = document.querySelectorAll('.slider .item');
let next =  document.getElementById('next');
let prev = document.getElementById('prev');

let active = 3;
function loadshow(){
    let stt = 0;
    items[active].style.transform = `none`;
    items[active].style.zIndex = 1;
    items[active].style.filter = 'none';
    items[active].style.opacity = 1;
    for(var i = active + 1; i < items.length; i++){
      stt++;
      items[i].style.transform = `translateX(${120 * stt}px)scale(${1 - 0.2 * stt}) perspective(16px) rotateY(-1deg)`;
      items[i].style.zIndex = -stt;
      items[i].style.filter = 'blur(5px)';
      items[i].style.opacity = stt > 2 ? 0 : 0.6;
  }
  stt = 0;
  for(var i = active - 1; i >= 0; i--){
    stt++;
    items[i].style.transform = `translateX(${120 * stt}px)scale(${1 - 0.2 * stt}) perspective(16px) rotateY(-1deg)`;
    items[i].style.zIndex = -stt;
    items[i].style.filter = 'blur(5px)';
    items[i].style.opacity = stt > 2 ? 0 : 0.6;
  }
  }
loadshow();
next.onclick = function(){
  active = active + 1 < items.length ? active + 1 : active;
  loadshow();
}

prev.onclick = function(){
  active = active - 1 >= 0 ? active - 1 : active;
  loadshow();
}

Embed on web page a Twitter Video, just like a YT video

(Complete beginner here, fighting to assemble some web page.)

If a “copy video address” in X (Twitter), I get something like:
https://x.com/i/status/1814440131505598541

If I get the embed code from a You Tube video, I get something like:

<iframe width="1280" height="720" src="https://www.youtube.com/embed/aNfD0dbiPSY" title="Oriented circles and relativistic geometry II | Wild Linear Algebra 35 | NJ Wildberger" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

My question is the following.

Using Javascript/html/css, if I wish to put the X (Twitter) video on web page, and have exacly the
same (or similar if not possible) embed result, as using the You Tube embed code, how can I achieve that ?

Thank you

(I do not know where to start from. I am grateful for any pointer or help)

Fetch Textures From a Collection

Hello everyone who’s reading.

I’m trying to create a website where I can mouse scroll through “cards” that are all in a single line, seen with a iso view from the side.

I’ve set up the scene in THREE.js, but I don’t know how to go about having a collection of elements that automatically get used as the card’s texture.

To explain better I’d like to:

  • Create and use an updatable collection of elements (images/videos)
  • Have each element of said collection get used as the texture for the front face of the boxes
  • Have the boxes size automatically adapt to the aspect ratio of the image texture
  • Not having to manually link each texture to each box, but instead each time I insert a new element in the collection, a new card, or box, is created and added to the scene

If someone can help, that would be much appreciated.

Thank you in advance!

Here’s the code I have right now:

import './style.css'
import * as THREE from 'three'

// Set up the scene
const canvas = document.querySelector('.webgl');
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff); // Set background color to white

// Create box geometry
const boxGeometry = new THREE.BoxGeometry(1, 1, 0.01);
//Create box material
const boxMaterial = new THREE.MeshStandardMaterial({
  transparent: true,
  opacity: 0.7

});

const numBoxes = 10; // Boxes number
const boxSpacing = 1; // Boxes spacing

// Create boxes mesh
for (let i = 0; i < 10; i++)
{
  const box = new THREE.Mesh(boxGeometry, boxMaterial);
    box.position.set(0, 0, -i * boxSpacing)  
    scene.add(box);
}

// Add ambient light to the scene
const ambientLight = new THREE.AmbientLight(0xffffff, 1); // Soft white light
scene.add(ambientLight);

// Set up the renderer
const renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);

// Set up the camera
const zoom = 300; // Adjust this value to control the zoom
const sizes = {
  width: window.innerWidth,
  height: window.innerHeight
}; // Declares sizes value as window sizes

const aspect = window.innerWidth / window.innerHeight; // Set aspect ratio to the window's
const camera = new THREE.OrthographicCamera(
  -sizes.width / zoom,
  sizes.width / zoom,
  sizes.height / zoom,
  -sizes.height / zoom,
  -10,
  1000
);

// const gridHelper = new THREE.GridHelper(100, 100, 0x444444, 0x444444);
// scene.add(gridHelper);

// Camera controls
camera.position.set(2, 2, 5);
camera.lookAt(0, 0, 0)

// Update camera aspect ratio and renderer size when the window is resized
window.addEventListener('resize', () => {
  // Update sizes
  sizes.width = window.innerWidth;
  sizes.height = window.innerHeight;

  // Update camera
  camera.left = -sizes.width / zoom;
  camera.right = sizes.width / zoom;
  camera.top = sizes.height / zoom;
  camera.bottom = -sizes.height / zoom;
  camera.updateProjectionMatrix();

  // Update renderer
  renderer.setSize(sizes.width, sizes.height);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});

// Render the scene
function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}
requestAnimationFrame(animate);

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mirko Pratofiorito</title>
  </head>
  <body>
    <div id="app"></div>
    <canvas class="webgl"></canvas>
    <script type="module" src="/main.js"></script>
  </body>
</html>

I would have tried something but unfortunately I’m fairly new to JS and don’t know where to start doing this.

How Can I Resolve the `npm i grpc` Installation Error in My Node.js gRPC Server Setup?

I’m trying to run a gRPC server with Node.js, using the following code:

const express = require("express");
const bodyParser = require("body-parser");
const grpc = require("grpc");
const protoLoader = require("@grpc/proto-loader");
const fs = require("fs");
const path = require("path");

const app = express();
const port = 3000;

const PROTO_PATH = path.join(__dirname, "message.proto");
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
});
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const Data = protoDescriptor.Data;

app.use(bodyParser.raw({ type: "application/x-protobuf" }));

app.post("/data", (req, res) => {
  try {
    const data = Data.decode(req.body);
    console.log(`Received data: ${JSON.stringify(data)}`);
    res.status(200).send("Data received");
  } catch (err) {
    console.error("Error decoding data:", err);
    res.status(400).send("Invalid data");
  }
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

One of the dependencies is grpc, and when I try to install it with npm i grpc, I encounter the following error:

npm error node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --library=static_library --module=/Users/wizardnet972/code/node-proto/node_modules/grpc/src/node/extension_binary/node-v115-darwin-arm64-unknown/grpc_node.node --module_name=grpc_node --module_path=/Users/wizardnet972/code/node-proto/node_modules/grpc/src/node/extension_binary/node-v115-darwin-arm64-unknown --napi_version=9 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v115' (1)

The full log is available here.

My Node.js version is:

node -v
v20.14.0

What can I do to resolve this issue?

Facing error in yarn install for isolated-vm on macOS

Trying to build Backstage App on my MacOS, one of its pre requisites is Yarn , But i am unsuccessful in trying to install it. Please help

I am encountering an error when running yarn install for a project on my macOS system. The error seems to be related to the isolated-vm package and involves node-gyp failing to build the module. Below is the error message I receive:

I also tried removing node modules and lock file using rm -r node_modules && rm yarn.lock && yarn install but it’s still failing.

System Details:

  • Operating System: macOS

  • Node.js Version: 18.20.4

  • Architecture: arm64

error /Users/vidhiyadav/Desktop/vidhi-devops/node_modules/isolated-vm: Command failed.
Exit code: 1
Command: prebuild-install || (node-gyp rebuild --release -j max && node-gyp clean)
Arguments:
Directory: /Users/vidhiyadav/Desktop/vidhi-devops/node_modules/isolated-vm
Output:
prebuild-install warn install No prebuilt binaries found (target=18.20.4 runtime=node arch=arm64 libc= platform=darwin)
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | darwin | arm64
gyp info find Python using Python version 3.9.12 found at "/Users/vidhiyadav/opt/anaconda3/bin/python3"

gyp info spawn /Users/vidhiyadav/opt/anaconda3/bin/python3
gyp info spawn args [
gyp info spawn args '/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/isolated-vm/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/vidhiyadav/Library/Caches/node-gyp/18.20.4/include/node/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/Users/vidhiyadav/Library/Caches/node-gyp/18.20.4',
gyp info spawn args '-Dnode_gyp_dir=/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp',
gyp info spawn args '-Dnode_lib_file=/Users/vidhiyadav/Library/Caches/node-gyp/18.20.4/<(target_arch)/node.lib',
gyp info spawn args '-Dmodule_root_dir=/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/isolated-vm',
gyp info spawn args '-Dnode_engine=v8',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.'
gyp info spawn args ]
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

Traceback (most recent call last):
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py", line 1501, in XcodeVersion
version_list = GetStdoutQuiet(["xcodebuild", "-version"]).splitlines()
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py", line 1562, in GetStdoutQuiet
raise GypError("Error %d running %s" % (job.returncode, cmdlist[0]))
gyp.common.GypError: Error 1 running xcodebuild

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/gyp_main.py", line 45, in <module>
sys.exit(gyp.script_main())
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/__init__.py", line 688, in script_main
return main(sys.argv[1:])
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/__init__.py", line 680, in main
return gyp_main(args)
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/__init__.py", line 665, in gyp_main
generator.GenerateOutput(flat_list, targets, data, params)
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py", line 2682, in GenerateOutput
writer.Write(
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py", line 912, in Write
self.WriteCopies(spec["copies"], extra_outputs, part_of_all)
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py", line 1308, in WriteCopies
env = self.GetSortedXcodeEnv()
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py", line 2279, in GetSortedXcodeEnv
return gyp.xcode_emulation.GetSortedXcodeEnv(
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py", line 1887, in GetSortedXcodeEnv
env = _GetXcodeEnv(
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py", line 1742, in _GetXcodeEnv
"XCODE_VERSION_ACTUAL": XcodeVersion()[0],
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py", line 1512, in XcodeVersion
version = CLTVersion()  # macOS Catalina returns 11.0.0.0.1.1567737322
File "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py", line 1550, in CLTVersion
return re.search(regex, output).groupdict()["version"]
AttributeError: 'NoneType' object has no attribute 'groupdict'
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.<anonymous> (/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/node-gyp/lib/configure.js:317:18)
gyp ERR! stack at ChildProcess.emit (node:events:517:28)
gyp ERR! stack at ChildProcess._handle.onexit (node:internal/child_process:292:12)
gyp ERR! System Darwin 23.5.0
gyp ERR! command "/Users/vidhiyadav/.nvm/versions/node/v18.20.4/bin/node" "/Users/vidhiyadav/Desktop/vidhi-devops/node_modules/.bin/node-gyp" "rebuild" "--release" "-j" "max"
gyp ERR! cwd /Users/vidhiyadav/Desktop/vidhi-devops/node_modules/isolated-vm