JavaScript Playwright how do i write a test that ensures an action results in one server call and not infinite server calls

I am writing a JavaScript application and using Playwright to test my application.

I found a bug in my code such that on selecting an item in a list, my app got stuck in an infinite loop calling a server API.

How can you write a playwright tests to ensure an action only causes a single server call.

Sample Code

I wait for the item to be visible using something like the following

await page.locator('list1','file1').waitFor();

Then I select and wait for the server request with code similar to beloe

const responsePromise = page.waitForResponse(resp => 
resp.url().includes('/myServerURL') && resp.status() === 200);
await page.locator('list1','file1').click();
const response = await responsePromise;

But i want to make sure that I only get one request to ‘/myServerURL’ on selecting the item, and not more than one.

Is this possible in Playwright

Unable to open a modal from within my teams application

I am create a teams application and is built using angular using the MDBootstrap packages. The application itself is hosted using AWS cloudfront.

Now the issue I am having is when I open a modal from within the application in teams I get the following error in the console:

Blocked a frame with origin “https://prod.code.myurl.com” from accessing a frame with origin “https://teams.microsoft.com”. Protocols, domains, and ports must match.

Note when the modal is opened I am not even calling any external api or anything.

This is how I am opening the modal:

  public openModal(formFileName: any) {
    const config = {
      modalClass: 'modal-xl',
      ignoreBackdropClick: true,
      animation: false,
      data: {
        title: 'FormLoader'
      },
    }
    let modalRef = this.modalService.open(FormLoaderModalComponent, config);
    modalRef.onClose.subscribe(async (message: any) => {
      console.log('Modal closed');
    });
  }
}

and this is the FormLoaderModalComponent:

import {Component} from '@angular/core';
import {MdbModalRef} from "mdb-angular-ui-kit/modal";

@Component({
  selector: 'app-form-loader-modal',
  templateUrl: './form-loader-modal.component.html',
  styleUrl: './form-loader-modal.component.scss'
})
export class FormLoaderModalComponent {
  title: string | null = null;
  formFileName: string | null = null;

  constructor(public modalRef: MdbModalRef<FormLoaderModalComponent>) {
  }
}



--- 
<div class="modal-header">
  <h5 class="modal-title" id="exampleModalLabel">{{ title }}</h5>
  <button
    type="button"
    class="btn-close"
    aria-label="Close"
    (click)="modalRef.close()"
  ></button>
</div>
<div class="modal-body">

</div>
<div class="modal-footer">
  <button type="button" class="btn btn-secondary" (click)="modalRef.close()">
    Close
  </button>
  <button type="button" class="btn btn-primary">Save changes</button>
</div>




so very basic but get the error.

Wondering what I might be doing wrong and how to fix the issue.

Thanks

super inconsistent animation in css and javascript

I want to make a scrolling button, where the text part scrolls out when you hover on it and scroll back when you stop hovering, but the animation is really inconsistent:

html

<div class="btn"><span class="button_circle"></span><button class="button" 
type="submit">SEND MESSAGE</button></div>

css

.btn{
display: flex;
align-items: center;
width: 150px;
}
.btn:hover{
 cursor: pointer;
.button{
    background-color: #3f51b5;
}
.button_circle{
    border-color: #3f51b5;
}
}
.button{
   background-color: #4f7b8a;
   border-radius: 20px;
   width: 0;
   color: #E5E4E2;
   position: relative;
   transform: translateX(-40px);
   z-index: 0;
   height: 25px;
   padding-left:30px ;
   font-size: 15px;
   text-align: center;

  }
  .full_length{
     width: 100px!important;
  }
  .no_length{
     width: 0px!important;
  }
  .button_circle{
    height: 40px;
    width: 40px;
    background-color: #bbb;
    border-radius: 50%;
    box-sizing: border-box;
    border: 2px solid #4f7b8a;
    display: inline-block;
    z-index: 1;
 }
  .move_btn{
     animation: appear 2s 0s 1 ease;
   }
  .del_btn{
     animation: dissapear 2s forwards;
    }
   @keyframes appear{
    0%{
     width: 0;
   }
   100%{
      width: 100px;
   }
  }
  @keyframes dissapear{
     0%{
       width: 100px;
   }
    100%{
      width: 0;
   }
   }

js

var is_transitioning = false;

$(".btn").hover(appear,dissappear);


function appear() {
    if (!is_transitioning) {
      is_transitioning = true;
      $(".button").removeClass("no_length");
      $(".button").removeClass("full_length");
      $(".button").removeClass("del_btn");
      $(".button").addClass("move_btn");
  
      setTimeout(function() {
        $(".button").addClass("full_length");
        $(".button").removeClass("move_btn");
        
      }, 2000); 
    }
  }
  function dissappear() {
      $(".button").removeClass("full_length");
      $(".button").addClass("del_btn");
      setTimeout(function() {
        $(".button").addClass("no_length");
        $(".button").removeClass("del_btn");
        is_transitioning = false; // Reset transition state after the transition
      }, 2000); // Time for disappear transition
    }

this works on the first cycle, but just breaks apart during the subsequent cycles, no_length somehow gets applied when I am still hovering over the button, and when I hover off the classList is somehow both no_length and full_length, sometimes the dissappear animation just does not get finished and the bar instantly dissappear, sometimes there is lag when I hover on the button, I have tried removing every class on hover and then applying them later, I have tried to add a is_transitioning state to stop it from continuesily being executed, but none of those seem to work. any suggestion is welcomed, thank you.

How can I execute js when loading a sub route on a static build in Sveltekit

I never noticed this before, but I’ve encountered a weird issue in my Sveltekit application. To put it simply, I have a ("/map") sub route that when refreshed/loaded directly as the sub route won’t execute any JS, I noticed this is the general case for all sub routes. when loading a sub route, no matter which one ("/about"), ("/map") it renders all the HTML and CSS perfectly but won’t execute any JS, UNLESS you load the root first ("/") and navigate via links or goTo to a sub route ("/map").

I’m using a static adapter, but this also happens with the adapter-auto. There is no issue in the dev environment, when running

npm run dev

but when testing the production build

npm run build

and running

npm run preview

the issue arises.

I want people to be able to load ("https://www.example.com/map") directly instead of having to go to ("https://www.example.com/") first and route from there just so that Sveltekit can execute the JS hence load the imports and other necesseties for the map to properly function and laod.

Chrome extension – create dynamic declarative net request ruleset

I want to create a chrome extension to start using the declarativeNetRequest API. I saw that it need a ruleset where each rule will have this structure

{
  "id" : 1,
  "priority": 1,
  "action" : { "type" : "block" },
  "condition" : {
    "urlFilter" : "abc",
    "initiatorDomains" : ["foo.com"],
    "resourceTypes" : ["script"]
  }
}

My idea is to have a dynammic set of rules that user can modify by adding or removing urls of websites. Is this possible, can I pass an obect instead of a static json file?

Render Tiptap Table from a custom node that renders Vue Component using VueNodeViewRenderer(VueComponent)

I am trying to extend tiptap table extention that renders a vuecomponent as I want to add a button obove the table. I am trying the following code and when I call setTable(), it does not renders a 3 row and columns table as it does when I remove the addNodeView function.

I want to be able to insert a default table using commands.insertTable({ rows: 3, cols: 3, withHeaderRow: true }) that renders vue component.

const table = Table.extend({
  name: tableNodeName,
  group: 'block',
  addExtensions () {
    return [TableCell, TableRow, TableHeader]
  },

  addOptions () {
    return {
      ...this.parent?.()
    }
  },
  addAttributes () {
    return {
      ...this.parent?.()
    }
  },
  renderHTML ({ HTMLAttributes }) {
    return ['div', { class: 'table-wrapper' }, ['table', HTMLAttributes, ['tbody', 0]]]
  },

  addNodeView () {
    return VueNodeViewRenderer(TiptapTable)
  },

  addCommands () {
    return {
      ...this.parent?.(),
      setTable: () => ({ commands }) => commands.insertTable({ rows: 3, cols: 3, withHeaderRow: true })
    }
  }
})

TiptapTable.vue

<script setup lang="ts">
import { defineProps } from 'vue'
import { NodeViewWrapper, NodeViewContent, nodeViewProps } from '@tiptap/vue-3'

// Define props from NodeViewProps
const props = defineProps({
  ...nodeViewProps
})
</script>

<template>
  <NodeViewWrapper>
    <h2>Table</h2>
    <table>
      <NodeViewContent as="tbody" />
    </table>
  </NodeViewWrapper>
</template>

Discord.js: My code throws “” is not a fucntion error

I am writing a private bot. When I wanted to make a command with option to ping another user. However, when I try to run it i am getting an error:
TypeError: " " is not a function
This is my code:

const { Client, Events, GatewayIntentBits, SlashCommandBuilder, REST, Routes } = require('discord.js');
const {token} = require('./config.json');

const client = new Client({intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers]}); 

client.once(Events.ClientReady, c => {
    console.log(`Logged in as ${c.user.tag}`);

    const ping = new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Pings another user')
        .addUserOption(option =>
            option
                .setName('pingd')
                .setDescription('Who to ping?')
                .setRequired(false)
        )
        .setIntegrationTypes(0, 1)
        .setContexts(0, 1, 2);
        

    const noni = new SlashCommandBuilder()
        .setName('noni')
        .setDescription('Test command')
        .setIntegrationTypes(0, 1)
        .setContexts(0, 1, 2);

    client.application.commands.create(ping);
    client.application.commands.create(noni);
});


client.on(Events.InteractionCreate, interaction => {
    if(!interaction.isChatInputCommand()) return;
    if(interaction.commandName === "ping"){
        let user = interaction.options.getUser('pingd'); 
        if (!user) user = interaction.user;
        console.log(user)
        interaction.reply(` ``test``n @${user.username}`);
    }
    if(interaction.commandName === "noni"){
        interaction.reply(` ``another test!`` `);
    }
    console.log(interaction);
});

client.login(token);

How can i fix it?
Thanks

I have tried to remove @${user.username} section, but it didn’t work.

Can set breakpoints in .js files in vscode only after started vite debugger?

Why I can only set valid breakpoints in .js files in vscode AFTER starting the vite (node.js) debugger?
Not working:

  1. npx vite (starting the server)
  2. Set breakpoint in vscode
  3. Start Debugger with F5
  4. New chrome window opens

Debugger does start but not react, only stoppable

Working:

  1. npx vite (starting the server)
  2. Start Debugger with F5
  3. Set breakpoint in vscode
  4. New chrome window opens

Debugger stopps at breakpoint and variables are visible. But with this methode I can only debug functions which are called after all initialisations?

// vite.config.js
import { defineConfig } from 'vite';
import dns from 'dns'

dns.setDefaultResultOrder('verbatim')

export default defineConfig({
    server: {
        host: '127.0.0.1',
        port: 3000
    },
    build: {
        outDir: 'dist',
        emptyOutDir: true,
        rollupOptions: {
            input: {
                main: 'js/main.js',
            },
            output: {
                entryFileNames: 'bundle.js',
                assetFileNames: false,
            },
        },
        sourcemap: false
    },
    publicDir: false,
    css: false,
});

// launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:3000",
            "enableContentValidation": false,
            "webRoot": "${workspaceFolder}",
            "sourceMapPathOverrides": {
                "webpack:///src/*": "${workspaceFolder}/*",
                "webpack:///js/*": "${workspaceFolder}/js/*"
            },
            "trace": true
        }
    ]
}

Any idea? Thanks…

How do I get esbuild to stop renaming things?

In upgrading my SpreeCommerce app, I’ve been trying to use esbuild as the JS bundler. I’m treating the Spree frontend JS files as a vendor directory in the app, trying to get esbuild to bundle the files I need. At this point esbuild bundles the files, but winds up renaming the namespace/function Spree to Spree2 when encountering it. This results in the error Uncaught ReferenceError: Spree is not defined.

Spree is defined here: https://github.com/spree/spree_rails_frontend/blob/4-5-stable/app/assets/javascripts/spree/frontend/main.js. Confirmed using esbuild 0.24.0. Thoughts and attempts based on what I’ve read on the topic:

  • Are some of the methods defined there conflicting with esbuild?
  • Is esbuild somehow reading the namespace from the Rails side of the
    application and thinking there’s a conflict?
  • Tried changing the function Spree line to export function Spree () {}
  • Tried export { Spree } from './vendor/spree/frontend/main.js' in application.js
  • Tried setting keepNames: true, in esbuild config options
  • Tried changing the load order and plenty other things which only resulted in more errors

build/application.js:

  // app/assets/javascripts/vendor/spree/frontend/main.js
  var import_jsuri2 = __toESM(require_Uri());
  var import_jsuri3 = __toESM(require_Uri());
  function Spree2() {
  }
  console.log("main.js");
  Spree2.ready = function(callback) {

Import Uri from 'Jsuri' has also not been working properly, but that’s a simpler issue to fix. Would appreciate other suggestions to try, other than renaming Spree to Spree2 in the rest of the JS (yikes!)

get variable under Network tab on browser using jQuery [duplicate]

I have a simple search submission form on one page with the following code…

<form id="FormSearch" method="POST" class="customform" action="forum-search.php">
    <label for="SearchWord" class="topLabel SearchPage">Search Forum
        <input type="text" name="SearchWord" id="SearchWord" placeholder="Search...">
    </label>
</form>

When a search term is submitted, you are sent to forum-search.php which is where I want jQuery or JavaScript to handle the results of the search.
Under the network tab on my browser, I can see SearchWord: ‘word searched’ How can I use jQuery or JavaScript to access the SearchWord variable?

Why is my query call returning extra data that I didn’t request?

I have an issue where changing the status of a turn causes it to appear in other views where it shouldn’t. For example, if I set a turn in ‘technical support’ to ‘pending,’ it also appears in ‘payment’ and ‘inquiry,’ even though it should only be shown in the designated view without altering the data.

function setupSocketHandlers(socket) {
    const handleDatabaseQuery = async (query, params) => {
        try {
            const res = await pool.query(query, params);
            return res.rows;
        } catch (error) {
            console.error('Database query error:', error);
            throw error;
        }
    };

// Función para obtener los turnos por destino
const getTurnosByDestino = async (destino) => {
    try {
      return await handleDatabaseQuery(
        'SELECT * FROM turnos WHERE DESTINO = $1 AND ESTADO = $2 OR ESTADO = $3 OR ESTADO = $4 ORDER BY CREADO_A ASC',
        [destino, 'PENDIENTE', 'ATENDIENDO', 'LLAMANDO']
      );
    } catch (error) {
      throw new Error(`Error fetching turnos for destino ${destino}`);
    }
  };
// Emitir el evento para que los clientes recarguen la lista de turnos
io.emit('turnosActualizados'); // Este evento se usará para refrescar la vista
  // Consulta para "Técnica"
  socket.on('getUsuarioTecnica', async () => {
    try {
      const turnos = await getTurnosByDestino('TECNICA');
      socket.emit('respuestaUsuarioTecnica', turnos);
    } catch (error) {
      socket.emit('error', 'Error fetching turnos de tecnica');
    }
  });
  
  // Consulta para "Pagos"
  socket.on('getUsuarioPagos', async () => {
    try {
      const turnos = await getTurnosByDestino('PAGO');
      socket.emit('respuestaUsuarioPagos', turnos);
    } catch (error) {
      socket.emit('error', 'Error fetching turnos de pagos');
    }
  });
  
  // Consulta para "Consulta"
  socket.on('getUsuarioConsulta', async () => {
    try {
      const turnos = await getTurnosByDestino('CONSULTA');
      socket.emit('respuestaUsuarioConsulta', turnos); 
    } catch (error) {
      socket.emit('error', 'Error fetching turnos de consulta');
    }
  });

// Crear turno  
socket.on('crearTurno', async (body) => {
    const { DNI, DESTINO } = body;
    try {
      const nuevoTurno = await handleDatabaseQuery(
        'INSERT INTO turnos (DNI, DESTINO, ESTADO) VALUES ($1, $2, $3) RETURNING *',
        [DNI, DESTINO, 'PENDIENTE']
      );
      
      // Emitir los turnos actualizados a todos los clientes
      io.emit('turnosActualizados');  // Esto emite a todos los clientes conectados
      socket.emit('respuestaCrearTurno', nuevoTurno); // Emitir la respuesta al cliente que lo solicitó
    } catch (error) {
      console.error(error);  // Mostrar el error en consola para más detalles
      socket.emit('error', 'Error creando turnos');
    }
  });
  

socket.on('actualizarEstadoDelTurno', async (body) => {
    const { id, ESTADO } = body;
    try {
      const turnoActualizado = await handleDatabaseQuery(
        'UPDATE turnos SET ESTADO = $1, creado_a = NOW() WHERE id = $2 RETURNING *',
        [ESTADO, id]
      );
  // Emitir el evento para que los clientes recarguen la lista de turnos
io.emit('turnosActualizados'); // Este evento se usará para refrescar la vista
      socket.emit('respuestaActualizarEstado', turnoActualizado);
    } catch (error) {
      socket.emit('error', 'Error actualizando el estado del turno');
    }
  });
  
  socket.on('comentarTurno', async (body) => {
    const { id, comentario } = body;
    try {
      const turnoActualizado = await handleDatabaseQuery(
        'UPDATE turnos SET comentario = $1 WHERE id = $2 RETURNING *',
        [comentario, id]
      );
      // Emitir el evento para que los clientes recarguen la lista de turnos
      io.emit('turnosActualizados'); // Este evento se usará para refrescar la vista
  
      socket.emit('respuestaComentarTurno', turnoActualizado);
    } catch (error) {
      socket.emit('error', 'Error comentando el turno');
    }
  });

  const getTurnosByDestinoComentarios = async (destino) => {
    try {
      return await handleDatabaseQuery(
        'SELECT * FROM turnos WHERE DESTINO = $1 AND ESTADO = $2 AND comentario IS NOT NULL ORDER BY CREADO_A ASC',
        [destino, 'LISTO']
      );
    } catch (error) {
      throw new Error(`Error fetching turnos for destino ${destino}`);
    }
  };
  // Emitir el evento para que los clientes recarguen la lista de turnos
io.emit('turnosActualizados'); // Este evento se usará para refrescar la vista
  // Consulta para "Técnica comentados"
  socket.on('getUsuarioTecnicaComentado', async () => {
    try {
      const turnos = await getTurnosByDestinoComentarios('TECNICA');
      socket.emit('respuestaResponderTurnoTecnica', turnos);
    } catch (error) {
      socket.emit('error', 'Error fetching turnos de tecnica');
    }
  });
  
  // Consulta para "Pagos comentados"
  socket.on('getUsuarioPagosComentado', async () => {
    try {
      const turnos = await getTurnosByDestinoComentarios('PAGO');
      socket.emit('respuestaResponderTurnoPago', turnos);
    } catch (error) {
      socket.emit('error', 'Error fetching turnos de pagos');
    }
  });
  
  // Consulta para "Consulta comentados"
  socket.on('getUsuarioConsultaComentado', async () => {
    try {
      const turnos = await getTurnosByDestinoComentarios('CONSULTA');
      socket.emit('respuestaResponderTurnoConsulta', turnos); 
    } catch (error) {
      socket.emit('error', 'Error fetching turnos de consulta');
    }
  }); 
  }
io.on('connection', (socket) => {
setupSocketHandlers(socket);
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Return, object property “undefined” “Cannot GET /src/html/undefined” on a Link

within the return statement there is a link element that has an object property as its value/href.
This link is wrapped around each item in my array. When the link is clicked “Cannot GET /src/html/undefined”

   const displayMovies = (Movies) => {
    const htmlString = Movies
        .map((item) => {
            return `
            <div class="Media-Card">
                <a href='${item.page}'><img class='Poster' src="${item.poster}" ></img></a>
                <h1 class='Media-Card-Header'>${item.title}</h1>
            </div>
        `;
        })
        .join('');
    searchlist.innerHTML = htmlString;
};

Within my object class, I have declared and assigned a value for href.

   this.page = page;

google sign in pop up appears two times

when i click on in sign in it appears two time, first pop up give me log (handleCredentialResponse called) . and the second pop up do rest of the work really frusted with this bug.



<!-- Google Identity Services Library and Initialization Script -->
<script>
  (function () {
    // Check if Google Sign-In has already been initialized
    if (window.googleSignInInitialized) {
      console.log("Google Sign-In has already been initialized.");
      return;
    }

    // Set a flag to indicate initialization has started
    window.googleSignInInitialized = true;

    // Function to initialize Google Sign-In
    function initializeGoogleSignIn() {
      console.log("Initializing Google Sign-In.");

      // Replace these placeholders with your actual values
      const GOOGLE_CLIENT_ID = "XXXX"; // Your Google OAuth Client ID
      const CLOUD_RUN_BASE_URL = "XXXX"; // Your Cloud Run service URL

      /**
       * Function to handle credential response from Google Sign-In
       * @param {Object} response - The credential response from Google
       */
      function handleCredentialResponse(response) {
        console.log("handleCredentialResponse called.");
        // Extract the ID token from the response
        const idToken = response.credential;

        // Initialize the token client to request an OAuth access token
        const tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: GOOGLE_CLIENT_ID,
          scope: "https://www.googleapis.com/auth/business.manage",
          prompt: "", // No prompt to avoid additional pop-ups
          callback: (tokenResponse) => {
            if (tokenResponse.error) {
              console.error(
                "Error obtaining access token:",
                tokenResponse.error
              );
              return;
            }

            const accessToken = tokenResponse.access_token;
            console.log("Access Token:", accessToken);

            // Optionally, you can verify the ID token if needed
            fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${idToken}`)
              .then((res) => res.json())
              .then((data) => {
                if (data.email) {
                  const email = data.email;
                  const name = data.name || "No Name Provided";
                  console.log("User Email:", email);
                  console.log("User Name:", name);

                  // Start the data processing flow
                  processUserData(email, name, accessToken);
                } else {
                  console.error("Unable to retrieve user information.");
                }
              })
              .catch((err) => {
                console.error("Error verifying ID token:", err);
              });
          },
        });

        // Request the OAuth access token
        tokenClient.requestAccessToken();
      }

      /**
       * Function to process user data by fetching Google Business ID and storing data in Airtable
       * @param {string} email - User's email
       * @param {string} name - User's name
       * @param {string} accessToken - OAuth access token
       */
      function processUserData(email, name, accessToken) {
        console.log("Processing user data...");

        // Step 1: Fetch Google Business ID
        fetch(`${CLOUD_RUN_BASE_URL}/fetch-google-business-id`, {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        })
          .then((response) => response.json())
          .then((accountData) => {
            if (accountData.accounts && accountData.accounts.length > 0) {
              const googleBusinessId = accountData.accounts[0].name;
              console.log("Google Business ID:", googleBusinessId); // Log Business ID

              // Step 2: Store data in Airtable
              storeUserData(email, name, googleBusinessId, accessToken);
            } else {
              console.error("No Google Business accounts found.");
            }
          })
          .catch((error) => {
            console.error("Error fetching Google Business ID:", error);
          });
      }

      /**
       * Function to store user data in Airtable via backend
       * @param {string} email - User's email
       * @param {string} name - User's name
       * @param {string} googleBusinessId - Google Business ID
       * @param {string} accessToken - OAuth access token
       */
      function storeUserData(email, name, googleBusinessId, accessToken) {
        console.log("Storing user data in Airtable...");

        fetch(`${CLOUD_RUN_BASE_URL}/store-user-data`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${accessToken}`,
          },
          body: JSON.stringify({ email, name, googleBusinessId }),
        })
          .then((response) => {
            if (!response.ok) {
              return response.json().then((errData) => {
                throw new Error(errData.error || "Unknown error occurred.");
              });
            }
            return response.json();
          })
          .then((data) => {
            console.log("Data stored in Airtable:", data);
            // Optional: You can add more actions here, such as redirecting the user
            // window.location.href = '/welcome';
          })
          .catch((error) => {
            console.error("Error storing data in Airtable:", error);
          });
      }

      /**
       * Initialize the Google Sign-In button
       */
      google.accounts.id.initialize({
        client_id: GOOGLE_CLIENT_ID,
        callback: handleCredentialResponse,
        cancel_on_tap_outside: false,
      });

      google.accounts.id.renderButton(
        document.getElementById("g_id_signin"),
        { theme: "outline", size: "large", type: "standard" } // Customization options
      );

      // Optional: Automatically prompt the user to sign in
      google.accounts.id.prompt();
    }

    // Function to wait until the Google library is loaded
    function waitForGoogleLibrary(callback) {
      if (
        typeof google !== "undefined" &&
        google.accounts &&
        google.accounts.id
      ) {
        callback();
      } else {
        setTimeout(() => waitForGoogleLibrary(callback), 100);
      }
    }

    // Initialize Google Sign-In once the library is loaded
    waitForGoogleLibrary(initializeGoogleSignIn);
  })();
</script>


i have tried to change the code but nothing work also search in google nothing works. i also check chatgpt but could not find the bug. please help

Xano realtime SDK disconnects

I am using Xano realtime SDK in my react-native expo application. The SDK setup is done like this.

import 'react-native-url-polyfill'

import React, { useContext, useState, useEffect, createContext } from 'react';
import { Platform } from 'react-native'
import { XanoClient, XanoSessionStorage } from '@xano/js-sdk';
import * as GlobalVariables from '../config/GlobalVariableContext';
import AsyncStorage from '@react-native-async-storage/async-storage';


const XanoContext = createContext();
export function Xano({
    children
}) {

    const setGlobalVariableValue = GlobalVariables.useSetValue();
    const Constants = GlobalVariables.useValues();

    const [xano, setXano] = useState()

    useEffect(() => {
        if (Platform.OS == 'web') return
        const xano = new XanoClient({
            instanceBaseUrl: Constants["XANO_BASE_URL"],
            storage: AsyncStorage,
            realtimeConnectionHash: Constants["XANO_REALTIME_CONN_HASH"],
        });

        setXano(xano)[enter image description here](https://i.sstatic.net/ecjtPMvI.png)
    }, [])


    // set realtime token
    React.useEffect(() => {
        // console.log('token ', Constants['AUTH_TOKEN'])
        if (Constants['AUTH_TOKEN'] && xano) {
            const token = Constants['AUTH_TOKEN'].split(' ')[1]
            // console.log('setting token ', token)
            xano.setRealtimeAuthToken(token)


            console.log('realtime token', xano.hasRealtimeAuthToken());
        }

    }, [Constants['AUTH_TOKEN'], xano])




    const value = {
        xano
    }


    return (
        <XanoContext.Provider value={value}>
            {children}
        </XanoContext.Provider>
    )

}


The sdk sometime disconnects. How can I reconnect and when it does that. Also the realtime SDK doesn’t work in the PWA. I am getting this error.

I tried to find out a way to reconnect to sdk but the doc doesn’t provide any clue about how to do that.

Module not found: react-refresh/runtime.js falls outside of src/” Error When Compiling React App on Ubuntu

I’ve developed a React and Node.js application that compiles and runs smoothly on Windows. However, when I try to run it on my Ubuntu server, I keep encountering the following error:
Module not found: Error: You attempted to import /home/ubuntu/mesajapp/client/node_modules/react-refresh/runtime.js which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

What I’ve Tried
Deleting node_modules and package-lock.json:
I removed these files and reinstalled all dependencies with npm install.

Ensuring Compatibility Between Node.js and npm Versions:
My current Node.js version on Ubuntu is 18.19.1 with npm 10.9.0, while on Windows it’s Node.js 22.7.0 and npm 10.8.2. I attempted to install Node.js 22.7.0 on Ubuntu using nvm, but I faced difficulties as nvm was not found in my environment.

Config File Adjustments:
My project includes a config-overrides.js file where I set fallbacks for Webpack 5, particularly:

Unfortunately, this hasn’t resolved the issue.

Running the App:
Every attempt to run npm start on Ubuntu after reinstalling dependencies results in the same error.

Additional Info
The error message specifically points to react-refresh/runtime.js being outside the src/ directory, though it works fine on Windows.
I’ve tried different Node and npm configurations, as mentioned above, without success.

Any insights into what might be causing this issue or how to address it would be greatly appreciated! Thank you in advance.

Here is the GitHub repository for the project: github. It contains all the relevant files and structure where the issue occurs.