AWS Cognito initiateAuth response empty when trying to authenticate a user in JavaScript

I’m trying to authenticate a user with AWS Cognito using the USER_PASSWORD_AUTH flow in JavaScript. However, the response from initiateAuth is always empty. Here’s the code I’m using:

        var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({region: 'eu-central-1'});

        const poolData = {
            UserPoolId: "userPoolId",
            ClientId: "clientId",
        }

        let username = document.getElementById('username').value;
        let password = document.getElementById('password').value;
            var aws_params = {
            AuthFlow: "USER_PASSWORD_AUTH", 
            AuthParameters: {
                "PASSWORD": password, 
                "SECRET_HASH": "secretHash", 
                "USERNAME": username
            }, 
            ClientId: "clientId", 
        };

        response = cognitoidentityserviceprovider.initiateAuth(aws_params);

However, the response object is consistently empty, like this:

{
"request": {…},
"data": null,
"error": null,
"retryCount": 0,
"redirectCount": 0,
"httpResponse": {…},
"maxRetries": 3,
"maxRedirects": 10

}

I did the same thing but using a django view and it works: i got the token from cognito. But in js I’m stuck.

Any guidance is appreciated!

How do I make my ApexCharts reactive with data in Pinia Store using Vue.js 3 and composition API?

I am building a dashboard using Vue.js 3 and ApexCharts with the composition API. The data for the charts is held in a Pinia data store.

I have a function that pulls data from a sample .json file (which models what an API will return once it is set up), processes, and returns the data as a multidimensional array for the charts that is stored in the Pinia store.

The problem I’m having is when I run the function to update the data, I can see it update in the Pinia store via vue devtools, but the chart does not change to reflect the new values like the rest of the app does.

At the advice of other stack overflow answers, I’ve wrapped chart options and series in ref(). I’ve also read this post on GitHub, but as I’m fairly new to Vue and have only worked with the composition API, I’m unsure what exactly to implement in my code to make the charts reactive to Pinia data.

I have created a sample repo with a single chart and sample data on stackblitz showing the behavior I’m experiencing.

Chart options and series code:

let chartOptions = ref({
  chart: {
    id: "grocerChart",
    type: "bar",
    stacked: true,
    stackType: "100%",
    toolbar: {
      show: true,
      tools: {
        download: true,
        zoom: false,
        zoomin: true,
        zoomout: true,
        reset: true,
      },
    },
  },
  title: {
    text: storeData.selectedRegion,
    align: "center",
  },
  plotOptions: {
    bar: {
      horizontal: true,
    },
  },
  grid: {
    padding: {
      bottom: 20,
      right: 20,
      top: 5,
    },
  },
  xaxis: {
    categories: storeData.chartData[0], // ['Fruit', "Meat", "Vegetables"],
    tickPlacement: "on",
    labels: {
      rotate: 0,
      style: {
        fontSize: 10,
      },
    },
  },
  fill: {
    opacity: 1,
  },
  legend: {
    fontSize: 10,
    offsetX: 0,
    offsetY: 0,
  },
  dataLabels: {
    enabled: false,
  },
  noData: {
    text: "No Data",
    style: {
      fontSize: "24px",
    },
  },
});

let chartSeries = ref([
  {
    name: storeData.chartData[1][0][0], // 'fruit',
    data: storeData.chartData[1][0][1], // [10, 14, 10]
  },
  {
    name: storeData.chartData[1][1][0], // 'meat',
    data: storeData.chartData[1][1][1], // [10, 10, 4]
  },
  {
    name: storeData.chartData[1][2][0], // 'vegetable',
    data: storeData.chartData[1][2][1], // [9, 7, 12]
  },
]);

Pinia code:

import {ref} from 'vue'
import {defineStore} from 'pinia'

export const useDataStore = defineStore('data', () => {

    let selectedRegion = ref('No Region Selected');
    let chartData = ref([
        [],
        [
          [[], []],
          [[], []],
          [[], []]
        ]
    ]);

    return {
        selectedRegion,
        chartData
      }
})

Function to process model .json data and return multidimensional array for chart:

function updateData(data, selectedRegion) {
    // Filter data by selected state 
    const selStateData = data.filter(item => item.state === selectedRegion);

    // Extract and sort store names
    const stores = [...new Set(selStateData.map(item => item.store))].sort();

    // Extract and sort category values
    const categories = [...new Set(selStateData.map(item => item.category))].sort();

    // Initialize the result array for categorized data
    const categorizedData = categories.map(category => [category, Array(stores.length).fill(0)]);

    // Populate the categorized data
    selStateData.forEach(item => {
        const storeIndex = stores.indexOf(item.store);
        const categoryIndex = categories.indexOf(item.category);
        categorizedData[categoryIndex][1][storeIndex] += item.inventory;
    });

    return [stores, categorizedData];
}

Button to place the above data into Pinia store:

<v-btn 
 class="ma-3" 
 @click="storeData.chartData = updateData(grocerData, storeData.selectedRegion)"
>
  Update
</v-btn>

Any help is greatly appreciated!

Why are empty routes needed for this React Router code to work?

Using React (and React Router) I am creating a navigation menu inside of another navigation menu. I created exactly what I am looking for but I don’t understand part of the code and I want some clarity. The code I don’t understand is commented with: “why is this needed”.

As an experiment, I asked chat gpt to rewrite my code and it did so with the commented code removed, but that version does not work.

The code below works because it lets me select the LINK named Topology and this renders a component named Topology. Inside the rendered component are three additional links , when each of these are clicked a corresponding component is rendered.

I attached a little video of me clicking the links and the routes changing (for some reason the video didn’t capture my mouse cursor but the links I click are reflected in the URL change)

Video of render

import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';



function WorkSpace({children}){
  return(
    <div >
    <div>{children}</div>
    <h1>WORKSPACE</h1>
     </div>

  )
}

function Topology(){
  return(  
  
    <div  >

     <nav >
     <Link to="topology" >Topology</Link>
     <br/>
     <Link to="packet-broker"  >Packet Broker</Link>
     <br/>
     <Link to="slice" >Slice</Link>
    </nav>
    <h1>Topology</h1>

    <Routes>
      <Route path="topology" element={<h1>TOPOLOGY WINDOW</h1>}/> 
      <Route path="slice" element={<h1>SLICE WINDOW</h1>} /> 
      <Route path="packet-broker" element={<h1>Packet Broker WINDOW</h1>} /> 
    </Routes>

 
    </div>
  )
}


function MiniTabsRenderSpace(){

  return (
    <div>
    <Routes>
      <Route path="topology" element={<Topology />}> 
        <Route path="topology" element={<></>} />         // <--Why is this needed?
        <Route path="slice" element={<></>} />            // <--Why is this needed?
        <Route path="packet-broker" element={<></>} />    // <--Why is this needed? 
      </Route>
    </Routes>

    </div>
  );

}



function Nav() {
  return (
    <nav>
      <ul>
      <Link to="/topology">Topology</Link>
      <br/>
      <Link to="/another-link-1">Another Link-1</Link>
      <br/>
      <Link to="/another-link-2">Another Link-2</Link>
      </ul>
    </nav>
  );
}


function App() {
  return (

      <div>
        
          <Nav/>
          <WorkSpace>
          <MiniTabsRenderSpace/>
          </WorkSpace>
        
  
      </div>
  
  );
}

export default App;

how to prevent overlap in 2 input fields type=”number”

i have this html:

<span class="input-group-text pretext">Min:</span>          
<input min="" max="" type="number" class="form-control min-input" name="price_min" value="12">
<br />                              
<span class="input-group-text pretext">Max:</span>
<input min="" max="" type="number" class="form-control max-input" name="price_max" value="25">

js:

$(".min-input, .max-input").on("input change", function(e) {
    var minInput = $(".min-input").val();
    var maxInput = $(".max-input").val();
    if(minInput > maxInput || maxInput < minInput) {
        alert('overlap');   
    }
});

When you put the cursor in the max field at the end of 25 and delete the 5 from 25 with backspace, the remaining number is 2 and is less then the min-input value. But still doesn’t give me any notification “overlap”

What i am doing wrong?

Example fiddle

How to specify desired HKDF output length with `crypto.subtle.deriveKey`

The web crypto API defines two different KDF utilities, namely deriveBits and deriveKey. While the former allows you to specify the desired output length (RFC 5869 calls this parameter L), the latter doesn’t seem to do so.

I need to use HKDF with SHA-512 (as the spec I’m implementing requires this) in order to derive an HMAC-SHA256 key. In other words, 256 output bits are sufficient; but only deriveBits seems to have a corresponding parameter:

const baseKey = await crypto.subtle.importKey('raw', new Uint8Array(32), { name: 'HKDF' }, false, ['deriveKey', 'deriveBits'])
const salt = new Uint8Array(16)
const info = new Uint8Array(8)

// deriveBits → derives 256 bit:
const rawHmacKey1 = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-512', salt: salt, info: info }, baseKey, 256);
const hmacKey1 = await crypto.subtle.importKey('raw', rawHmacKey1, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
const exported1 = new Uint8Array(await crypto.subtle.exportKey('raw', hmacKey1));
console.log(btoa(exported1)) // MTgxLDEyLDgsMTExLDI3LDI0OCw4NSw3OCw0MywxMCw5MywyNDIsMTksMTg5LDE5MSwxNzMsMTM2LDEwMCwyMSwyMjcsMzksMTI2LDE3OSwxOTYsNTAsODYsNjEsMjcsMTQzLDIxMiwxOTksMjAz

// deriveKey → derives 512 bit:
const hmacKey2 = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-512', salt: salt, info: info }, baseKey, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
const exported2 = new Uint8Array(await crypto.subtle.exportKey('raw', hmacKey2));
console.log(btoa(exported2)) // MTgxLDEyLDgsMTExLDI3LDI0OCw4NSw3OCw0MywxMCw5MywyNDIsMTksMTg5LDE5MSwxNzMsMTM2LDEwMCwyMSwyMjcsMzksMTI2LDE3OSwxOTYsNTAsODYsNjEsMjcsMTQzLDIxMiwxOTksMjAzLDUwLDE4Myw3Miw4OSwyMDQsMTcsMzksMTY5LDE4OCw5Niw3NSw5NSwxMTMsMjQ3LDExNywxOTQsNDYsMTY0LDIyOSwyMTMsNzUsMjE5LDI0NCwyMjYsMjAwLDE2MCw5NCwxNCw3MiwxNjMsMTcwLDEwMg==

Note that when using deriveKey I explicitly specified { name: 'HMAC', hash: 'SHA-256' } as key usage parameter. Regardless the derived key length seems to solely depend on the specified hash algorithm (SHA-512 → 64 bytes).

As I would prefer to use deriveKey, my question is: How do I specify the desired output key size?

How to write parses which will not ask to log in

I want to parse data from site https://csfloat.com/search?def_index=4727 and i use puppeteer.

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await page.goto("https://csfloat.com/search?def_index=4727");

  let arr = await page.evaluate(() => {
    let text = document.getElementsByClassName("price ng-star-inserted")
    let array = []
    for (let i = 0; i < text.length; i++) {
      array.push(text[i].innerText)
    }

    console.log(array)
  })
})()

But the problem is that when i run this script, it opens it’s own browser and open this page, where i am not authorized, so i cant parse data beacuse even if i paste my login and password, i have to confirm this in steam, so, how can i do this from my browser where i am authorized or how can i fix this problem, maybe another library???

How to close navigation by clicking on the outside and refactoring Js?

Hi Im trying to build my own navigation with just pure HTML, CSS, Js. I pretty much got it working but my Js is not good and think it could be cleaner. The functionality I want is…

when you click a dropdown if there is another dropdown open it will close it. If you click outside the dropdown it will close it. I have achieved this but I think it could be cleaner. Also for the mobile nav I would like it to close when you click outside of the navigation which I have not achieved. Here is the github repository https://github.com/danbakerri/bulma-test and the actual site https://danbakerri.github.io/bulma-test/ to see it in action the script is at the bottom of the index page(using the Bulma framework for now)

this is the HTML for the dropdowns

  <div class="navbar-item has-dropdown" data-dropdown>
            <a
              class="navbar-link navbar-dropdown-link"
              aria-label="menu"
              aria-expanded="false"
            >
              More
            </a>

            <div class="navbar-dropdown">
              <a class="navbar-item"> About </a>
              <a class="navbar-item is-selected"> Jobs </a>
              <a class="navbar-item"> Contact </a>
              <hr class="navbar-divider" />
              <a class="navbar-item"> Report an issue </a>
            </div>
          </div>

and this is the js (it works the way I want it to but I think it could be cleaner any Ideas?)

  window.addEventListener("load", function () {
        // wait until the page loads before working with HTML elements
        document.addEventListener("click", function (event) {
          //click listener on the document
          document.querySelectorAll(".navbar-dropdown").forEach(function (el) {
            if (el !== event.target) el.classList.remove("is-active");
            // close any showing dropdown that isn't the one just clicked
          });
          document
            .querySelectorAll(".navbar-dropdown-link")
            .forEach(function (el) {
              if (el !== event.target) el.classList.remove("is-active");
              // close any showing dropdown that isn't the one just clicked
            });
          if (event.target.matches(".navbar-dropdown-link")) {
            event.target
              .closest(".has-dropdown")
              .querySelector(".navbar-dropdown")
              .classList.toggle("is-active");
          }
          if (
            event.target.matches(".navbar-dropdown-link") &&
            event.target.matches(".is-active")
          ) {
            event.target
              .closest(".has-dropdown")
              .querySelector(".navbar-dropdown")
              .classList.remove("is-active");
          }
          if (event.target.matches(".navbar-dropdown-link")) {
            event.target
              .closest(".has-dropdown")
              .querySelector(".navbar-dropdown-link")
              .classList.toggle("is-active");
          }
          // if this is a dropdown button being clicked, toggle the show class
        });
      });

and to open and close the nav in mobile I have the button

 <a
          role="button"
          class="navbar-burger"
          aria-label="menu"
          aria-expanded="false"
          data-target="navbarBasicExample"
        >
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
        </a>
      </div>
<div id="navbarBasicExample" class="navbar-menu">
<!--body of nav-->
</div>

and Js. I would like to edit this script so it closes when you click anywhere out side of the nav <div id="navbarBasicExample" class="navbar-menu"> any ideas? here is the script I have (taken from the bulma site

  document.addEventListener("DOMContentLoaded", () => {
        // Get all "navbar-burger" elements
        const $navbarBurgers = Array.prototype.slice.call(
          document.querySelectorAll(".navbar-burger"),
          0
        );

        // Add a click event on each of them
        $navbarBurgers.forEach((el) => {
          el.addEventListener("click", () => {
            // Get the target from the "data-target" attribute
            const target = el.dataset.target;
            const $target = document.getElementById(target);

            // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"

            el.classList.toggle("is-active");
            $target.classList.toggle("is-active");
          });
        });
      });

Any suggestions on how I could simplify my script and get the functionality of the nav closing when I click out of it would be greatly appreciated thanks!

Supabase Auth exchangeCodeForSession returns “invalid request: both auth code and code verifier should be non-empty”

Architecture:

This is Cross-Platform web-based (SEO focused) project, that was built in CSR due to bad performance using SSR w/ Capacitor framework.

Client: Svelte + Vite + Capacitor

Due to use of vanilla Svelte, to handle navigation our choice was “svelte-routing”, for building the app on both web and mobile (iOS and Android) we use Capacitor.

Server: Fastify + Supabase

Our server framework of choice was Fastify, as long w/ Supabase, and thus we need to use the Supabase Auth solutions, what prevent us from using tools like Capacitor Generic OAuth2.


Problem

Following the Supabase guide to implement Google OAuth2, when storing the user session, got an AuthApiError: “invalid request: both auth code and code verifier should be non-empty”


Packages:

// package.json
{
    ...,
    "dependencies": {
        "@fastify/compress": "^8.0.1",
        "@fastify/cookie": "^11.0.2",
        "@fastify/cors": "^10.0.2",
        "@fastify/env": "^5.0.2",
        "@fastify/formbody": "^8.0.2",
        "@fastify/multipart": "^9.0.2",
        "@fastify/static": "^8.0.4",
        "@supabase/ssr": "^0.5.2",
        "@supabase/supabase-js": "^2.47.16",
        "dotenv": "^16.4.7",
        "fastify": "^5.2.1",
        ...
    },
    "packageManager": "[email protected]"
}

Code

Front:

Google sign-in button:

// AuthFormFooter.svelte

<script>
    // -- IMPORTS

    ...

    // -- FUNCTIONS

    async function signInWithOAuth(
        provider
        )
    {
        ...

        try
        {
            let redirectionToUrl;

            switch ( platform )
            {
                case 'android':
                    redirectionToUrl = 'com.myapp://auth';
                    break;
                case 'ios':
                    redirectionToUrl = 'com.myapp://auth';
                    break;
                default:
                    redirectionToUrl = 'http://localhost:5173/auth';
            }

            let data = await fetchData(
                '/api/auth/open-auth',
                {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify( { provider, redirectionToUrl } )
                }
                );

            if ( data.error )
            {
                console.error( 'Server sign-in error:', data.error );
            }
            else
            {
                if ( data.url )
                {
                    window.location.href = data.url;
                }
                else
                {
                    console.error( 'Server sign-in error:', data );
                }
            }
        }
        catch ( error )
        {
            console.error( errorText, error );
        }
    }
</script>

<div class="auth-modal-socials">
    <div
        class="auth-modal-socials-item"
        on:click={() => signInWithOAuth( 'google' )}>
        <span class="google-logo-icon size-150"></span>
    </div>
</div>

Auth Callback:

// AuthPage.svelte

<script>
    // -- IMPORTS

    import { onMount } from 'svelte';
    import { fetchData } from '$lib/base';
    import { navigate } from 'svelte-routing';

    // -- FUNCTIONS

    async function authCallback(
        code,
        next
        )
    {
        try
        {
            let response = await fetchData(
                '/api/auth/callback',
                {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify( { code } )
                }
                );

            if ( response.success )
            {
                navigate( `/${ next.slice( 1 ) }`, { replace: true } );
            }
            else
            {
                console.error( 'Authentication failed' );
            }
        }
        catch ( error )
        {
            console.error( 'Error during authentication', error );
        }
    }

    onMount(
        async () =>
        {
            let params = new URLSearchParams( window.location.search );
            let code = params.get( 'code' );
            let next = params.get( 'next' ) || '/';
            if ( code )
            {
                await authCallback( code, next );
            }
            else
            {
                console.error( 'No code found in query params' );
            }
        }
        );
</script>

Server:

Supabase client configuration:

// supabase_service.js

class SupabaseService
{
    // -- CONSTRUCTORS

    constructor(
        )
    {
        this.client = null;
    }

    // -- OPERATIONS

    initalizeDatabaseClient(
        request,
        reply
        )
    {
        this.client = createServerClient(
            process.env.SUPABASE_DATABASE_URL,
            process.env.SUPABASE_DATABASE_KEY,
            {
                cookies:
                {
                    getAll()
                    {
                        return parseCookieHeader( request.headers.cookie ?? '' );
                    },
                    setAll( cookiesToSet )
                    {
                        cookiesToSet.forEach(
                            ( { name, value, options } ) =>
                            {
                                let serializedCookie = serializeCookieHeader( name, value, options );

                                reply.header( 'Set-Cookie', serializedCookie );
                            }
                            );
                    }
                },
                auth:
                {
                    flowType: 'pkce'
                }
            }
            );
    }

    // ~~

    getClient(
        request,
        reply
        )
    {
        return this.client;
    }
}

// -- VARIABLES

export let supabaseService
    = new SupabaseService();

Auth controller:

// authentication_controller.js

...

// -- FUNCTIONS

...

// ~~

async function openAuth(
    request,
    reply
    )
{
    reply.header( 'Access-Control-Allow-Credentials', true );
    reply.header( 'Access-Control-Allow-Origin', request.headers.origin );

    let { redirectionToUrl, provider } = request.body;

    try
    {
        let { data, error } = await supabaseService.getClient().auth.signInWithOAuth(
            {
                provider,
                options: { redirectTo: redirectionToUrl }
            }
            );

        if ( data.url )
        {
            let url = data.url;

            return reply.code( 200 ).send( { url } );
        }
        else
        {
            return reply.code( 400 ).send( { error: 'auth-sign-in-failed' } );
        }
    }
    catch ( error )
    {
        return reply.code( 500 ).send(
            {
                error: 'Server error', details: error
            }
            );
    }
}

// ~~

async function authCallback(
    request,
    reply
    )
{
    reply.header( 'Access-Control-Allow-Credentials', true );
    reply.header( 'Access-Control-Allow-Origin', request.headers.origin );

    let code = request.body.code;
    let route = request.body.route ?? '/';

    try
    {
        if ( code )
        {
            let { data, error } =
                await supabaseService.getClient().auth.exchangeCodeForSession( code );

            if ( error )
            {
                return reply.code( 400 ).send(
                    {
                        success: false,
                        error: error.message
                    }
                    );
            }

            return reply.code( 200 ).send(
                {
                    success: true,
                    route
                }
                );
        }
        else
        {
            return reply.code( 400 ).send(
                {
                    success: false,
                    error: 'No code provided'
                }
                );
        }
    }
    catch ( error )
    {
        return reply.code( 500 ).send(
            {
                success: false,
                error: 'Server error', details: error
            }
            );
    }
}

// ~~

...

// -- EXPORT

export
{
    ...,
    openAuth,
    authCallback,
    ...
}

Updated all packages, enabled flow type pkce, implemented getAll and setAll instead of get, set and remove on cookies options. But all for nothing, got the same error and couldn’t get the solution to this error

object looks translucent even though opacity is 1 in three js

Why is my three.js cube looking translucent when I change the metalness, roughness, and color even though opacity stays at 1.

The translucence only appears with a rectangle light, not a point light.

Watch the demo video and you’ll see the light appear on the outside as if the box was translucent.

<!DOCTYPE html>
<html>
<head>
    <title>Simple Rectangle Light</title>
    <style>
        body { margin: 0; }
        canvas { display: block; }
        #controls {
            position: fixed;
            top: 10px;
            left: 10px;
            background: rgba(0,0,0,0.7);
            padding: 10px;
            border-radius: 5px;
            color: white;
            font-family: Arial;
        }
    </style>
</head>
<body>
    <div id="controls">
        <label><input type="checkbox" id="rectLight" checked> Rectangle Light</label><br>
        <label><input type="checkbox" id="pointLight" checked> Point Light</label><br>
        <div>
            Rectangle Light Position:<br>
            X: <input type="range" id="rectX" min="-1" max="1" step="0.1" value="0"><br>
            Y: <input type="range" id="rectY" min="-1" max="0" step="0.1" value="-0.9"><br>
            Z: <input type="range" id="rectZ" min="-1" max="1" step="0.1" value="0"><br>
            Rectangle Light Rotation:<br>
            X: <input type="range" id="rectRotX" min="0" max="6.28" step="0.1" value="1.57"><br>
            Y: <input type="range" id="rectRotY" min="0" max="6.28" step="0.1" value="0"><br>
            Z: <input type="range" id="rectRotZ" min="0" max="6.28" step="0.1" value="0"><br>
            Rectangle Light Size:<br>
            Width: <input type="range" id="rectWidth" min="0.1" max="1.6" step="0.1" value="1.0"><br>
            Height: <input type="range" id="rectHeight" min="0.1" max="1.6" step="0.1" value="1.0">
        </div>
        <div>
            Material Properties:<br>
            Color: <input type="range" id="matColor" min="0" max="255" step="1" value="51"><br>
            Roughness: <input type="range" id="matRough" min="0" max="1" step="0.1" value="0.9"><br>
            Metalness: <input type="range" id="matMetal" min="0" max="1" step="0.1" value="0.0">
        </div>
    </div>
    <script type="importmap">
        {
            "imports": {
                "three": "https://unpkg.com/[email protected]/build/three.module.js",
                "three/examples/jsm/controls/OrbitControls.js": "https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js",
                "three/examples/jsm/lights/RectAreaLightUniformsLib.js": "https://unpkg.com/[email protected]/examples/jsm/lights/RectAreaLightUniformsLib.js",
                "three/examples/jsm/helpers/RectAreaLightHelper.js": "https://unpkg.com/[email protected]/examples/jsm/helpers/RectAreaLightHelper.js"
            }
        }
    </script>
    <script type="module">
        import * as THREE from 'three';
        import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
        import { RectAreaLightUniformsLib } from 'three/examples/jsm/lights/RectAreaLightUniformsLib.js';
        import { RectAreaLightHelper } from 'three/examples/jsm/helpers/RectAreaLightHelper.js';

        // Scene setup
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x000000);

        // Camera setup
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.z = 5;

        // Renderer setup
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        // Initialize rect area light uniforms
        RectAreaLightUniformsLib.init();

        // Controls
        const controls = new OrbitControls(camera, renderer.domElement);

        // Comment out texture loading
        // const textureLoader = new THREE.TextureLoader();
        // const skinTexture = textureLoader.load('skin-image.png');

        // Add material definition before box creation
        const material = new THREE.MeshStandardMaterial({ 
            color: 0x333333,
            roughness: 0.9,
            metalness: 0.0,
            opacity: 1.0,
            transparent: false
        });

        // Create box
        const outerSize = 2;
        const thickness = 0.2;  // Back to original thickness
        const box = new THREE.Group();

        // Bottom
        const bottom = new THREE.Mesh(
            new THREE.BoxGeometry(outerSize, thickness, outerSize),
            material
        );
        bottom.position.y = -outerSize/2; 
        box.add(bottom);

        // Front wall
        const front = new THREE.Mesh(
            new THREE.BoxGeometry(outerSize, outerSize, thickness),
            material
        );
        front.position.z = outerSize/2 - thickness/2;
        front.position.y = -thickness/2;
        box.add(front);

        // Back wall
        const back = new THREE.Mesh(
            new THREE.BoxGeometry(outerSize, outerSize, thickness),
            material
        );
        back.position.z = -outerSize/2 + thickness/2;
        back.position.y = -thickness/2;
        box.add(back);

        // Left wall
        const left = new THREE.Mesh(
            new THREE.BoxGeometry(thickness, outerSize, outerSize),
            material
        );
        left.position.x = -outerSize/2 + thickness/2;
        left.position.y = -thickness/2;
        box.add(left);

        // Right wall
        const right = new THREE.Mesh(
            new THREE.BoxGeometry(thickness, outerSize, outerSize),
            material
        );
        right.position.x = outerSize/2 - thickness/2;
        right.position.y = -thickness/2;
        box.add(right);

        scene.add(box);

        // Rectangle light at bottom
        const width = 1.0;   // Smaller than inner width (was 1.8)
        const height = 1.0;  // Make it square like the box (was 1.8)
        const intensity = 10;
        const rectLight = new THREE.RectAreaLight(0xff0000, intensity, width, height);
        rectLight.position.set(0, -0.9 + 0.01, 0); // Keep it just above bottom
        rectLight.rotation.x = Math.PI / 2; // Face up
        scene.add(rectLight);

        // Add visible helper for the light
        const helper = new RectAreaLightHelper(rectLight);
        rectLight.add(helper);

        // Move ambient light before PMREM setup
        const ambientLight = new THREE.AmbientLight(0xffffff, 2.0);
        scene.add(ambientLight);

        // Add point light inside box
        const pointLight = new THREE.PointLight(0xff0000, 10.0);
        pointLight.position.set(0, -0.5, 0);
        pointLight.distance = 3;  // How far the light reaches
        pointLight.decay = 1;     // How quickly it fades with distance
        scene.add(pointLight);

        // Make the visualization sphere bigger
        const sphereGeometry = new THREE.SphereGeometry(0.2, 16, 16);  // Increase from 0.05 to 0.2
        const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
        const lightSphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        lightSphere.position.copy(pointLight.position);
        scene.add(lightSphere);

        // Animation
        function animate() {
            requestAnimationFrame(animate);
            controls.update();
            renderer.render(scene, camera);
        }
        animate();

        // Handle window resize
        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        });

        document.getElementById('rectLight').addEventListener('change', (e) => {
            rectLight.visible = e.target.checked;
            helper.visible = e.target.checked;
        });

        document.getElementById('pointLight').addEventListener('change', (e) => {
            pointLight.visible = e.target.checked;
            lightSphere.visible = e.target.checked;
        });

        document.getElementById('rectX').addEventListener('input', (e) => {
            rectLight.position.x = parseFloat(e.target.value);
            updateURL();
        });

        document.getElementById('rectY').addEventListener('input', (e) => {
            rectLight.position.y = parseFloat(e.target.value) + 0.01; // Keep slight offset from bottom
        });

        document.getElementById('rectZ').addEventListener('input', (e) => {
            rectLight.position.z = parseFloat(e.target.value);
        });

        document.getElementById('rectRotX').addEventListener('input', (e) => {
            rectLight.rotation.x = parseFloat(e.target.value);
        });

        document.getElementById('rectRotY').addEventListener('input', (e) => {
            rectLight.rotation.y = parseFloat(e.target.value);
        });

        document.getElementById('rectRotZ').addEventListener('input', (e) => {
            rectLight.rotation.z = parseFloat(e.target.value);
        });

        document.getElementById('rectWidth').addEventListener('input', (e) => {
            rectLight.width = parseFloat(e.target.value);
            helper.update(); // Update the helper to show new size
        });

        document.getElementById('rectHeight').addEventListener('input', (e) => {
            rectLight.height = parseFloat(e.target.value);
            helper.update(); // Update the helper to show new size
        });

        document.getElementById('matColor').addEventListener('input', (e) => {
            const value = parseInt(e.target.value);
            material.color.setRGB(value/255, value/255, value/255);
            updateURL();
        });

        document.getElementById('matRough').addEventListener('input', (e) => {
            material.roughness = parseFloat(e.target.value);
        });

        document.getElementById('matMetal').addEventListener('input', (e) => {
            material.metalness = parseFloat(e.target.value);
        });

        // Add function to update URL with current settings
        function updateURL() {
            const params = new URLSearchParams();
            
            // Material settings
            params.set('color', document.getElementById('matColor').value);
            params.set('rough', document.getElementById('matRough').value);
            params.set('metal', document.getElementById('matMetal').value);
            
            // Light visibility
            params.set('rectVisible', document.getElementById('rectLight').checked);
            params.set('pointVisible', document.getElementById('pointLight').checked);
            
            // Rectangle light settings
            params.set('rectX', document.getElementById('rectX').value);
            params.set('rectY', document.getElementById('rectY').value);
            params.set('rectZ', document.getElementById('rectZ').value);
            params.set('rectRotX', document.getElementById('rectRotX').value);
            params.set('rectRotY', document.getElementById('rectRotY').value);
            params.set('rectRotZ', document.getElementById('rectRotZ').value);
            params.set('rectWidth', document.getElementById('rectWidth').value);
            params.set('rectHeight', document.getElementById('rectHeight').value);
            
            window.history.replaceState({}, '', `${window.location.pathname}?${params.toString()}`);
        }

        // Also add function to load settings from URL on page load
        function loadFromURL() {
            const params = new URLSearchParams(window.location.search);
            
            // Helper function to load a parameter
            function loadParam(id, prop, obj, converter = parseFloat) {
                if(params.has(id)) {
                    const value = converter(params.get(id));
                    document.getElementById(id).value = value;
                    if(obj && prop) obj[prop] = value;
                }
            }
            
            // Load all parameters
            loadParam('color', null, null, value => {
                const v = parseInt(value);
                material.color.setRGB(v/255, v/255, v/255);
                return v;
            });
            loadParam('rough', 'roughness', material);
            loadParam('metal', 'metalness', material);
            loadParam('rectX', 'x', rectLight.position);
            // ... etc for all parameters
        }

        // Call on page load
        loadFromURL();
    </script>
</body>
</html> 

NodeJS throwring error “URL from user-controlled data”

I am using the below code which is properly sanitizing the url.

But still I keep getting Sonar Exception “Change this code to not construct the URL from user-controlled data.”

The line await fetch(sanitizedURL, options) is throwing Sonar exception.

I have tried if(!sanitizedCode) { throw Error .. } but it is also not working.

What modification is needed in the below code to resolve the issue?

function sanitizeURL(inputURL) {
    try {
        const parsedURL = new URL(inputURL);
        const domainsList = [inputURL];

        if (!schemesList.includes(parsedURL.protocol)) {
            throw new Error('Invalid URL scheme');
        }

        if (!domainsList.some(domain => domain.includes(parsedURL))) {
            throw new Error("URL not in allowed list");
        }

        return parsedURL.toString();
    } catch (error) {
        console.log("Caught error: ", error);
        throw error;
    }
}

async function fetchWithCheck(url, options = {}, responseType = "json", errorMessage = null) {
    let data;

    try {
        const sanitizedURL = sanitizeURL(url);
        const response = await fetch(sanitizedURL, options);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        switch (responseType) {
            case "json":
                data = await response.json();
                break;
            default:
                throw new Error(`Unsupported response type: ${responseType}`);
        }
        return data;
    } catch (error) {
        console.log(logMessage, error);

        const newError = new Error("problem fetching data");
        newError.cause = error;
        throw newError;
    }
}

How to Determine if Text is Overflowing & Handle Text Ellipses Removing the Overflow

I’m trying to write a function that determines whether the text has overflowed (to determine whether I should show a tooltip). How can I handle text ellipsis removing the overflow?

I have:

const isTextOverflowing = (element) => element.scrollWidth > element.clientWidth;

This works in all cases apart from when the text is truncated with ellipsis and is the same number of characters with and without ellipsis and so the text element’s scrollWidth equals the clientWidth (and incorrectly returns false).

Note: I add ellipsis to overflowing text with this css className:

clampTextInOneLine: {
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
    overflow: "hidden",
  },

Changing proxy in FindProxyForURL on request

We have a web scraper project that uses different proxies for each of the websites. Currently we’re using this code to return same proxy for each of the websites, but now we need to specify a separate proxy URL for each one:

var config = {
    mode: "pac_script",
    pacScript: {
        data: "function FindProxyForURL(url, host) {n" +
            "    let domainList = ['site1.com', 'site2.com',  'site3.com'];n" +
            "      if (host === 'www.google.com' || host === 'analytics.google.com')" +
            "           return 'PROXY pr.oxylabs.io:7777';" +
            "    for (let i = 0; i < domainList.length; i++) {n" +
            "n" +
            "        if (dnsDomainIs(host, domainList[i])) {n" +
            "            return 'PROXY pr.oxylabs.io:7777';n" +
            "        }n" +
            "    }n" +
            "    if (dnsDomainIs(host, 'analytics.google.com') || dnsDomainIs(host, 'doubleclick.net')) {" +
            "       return 'PROXY 127.0.0.1:65500';n" +
            "}n" +
            "   return 'DIRECT';n" +
            "}"
    }
};

This config is being loaded into browser’ settings via:

chrome.proxy.settings.set({value: config, scope: "regular"}, function () {});

and credentials were provided via:

function callbackFn(details) {
    let username = "custom-username-" + makeid(6);
    return {
        authCredentials: {
            username: username,
            password: "our_password"
        }
    };
}

and then we kept track of how many requests were made to each domain via:

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        if (details.method === "GET" && details.type === "main_frame") {
        }
    },
    {urls: ["<all_urls>"]},
);

The question is – how can we assign a different proxy to each domain when, for example, we pass in a magic string in the URL (for example, ___CHANGE___PROXY___FOR___DOMAIN___ZZZ), or something similar to indicate which domain needs a proxy change?

My idea was to create a function that returns contents for FindProxyForURL that generates javascript for it, then put it into config.pacScript.data and call chrome.proxy.settings.set({value: config, scope: "regular"}, function () { })

How can I get a PixelsObject from a Texture in Incisor?

I’m following the Incisor API documentation to create a PixelsObject from a graphic. I’ve confirmed that pawn.png is in my Assets directory and visible in LiveView. However, I’m getting an exception on the second line of code, and the console log is never displayed.

Here’s a simple block of code that will reproduce the error:

class ProjectMain {
    init() {
        let pawn = new GraphicObject(nc.graphicAssets.pawn, nc.mainScene, "Pawn");
        let pawnPixelsObject = nc.pixelsObjects.getPixelsObject(pawn.materialMaster.mainTexture);
        console.log(pawnPixelsObject);
    }
}

Can anyone help me understand why an exception occurs?

Javascript stream text in small chunks

I’m using a Vue.js app to read text from a server. The server streams small amounts of text with each request. For example, the total request lasts 10 seconds and the server writes 1 word per second to the stream.

I’ve tried this:

fetch('https://my-streaming-api').then(response => {
const reader = response.body.getReader();

async function readStream() {
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    // Process the chunk here (e.g., display it)
    console.log('Chunk:', value); 
  }
}

readStream();
});

The problem I have is that the read() function will block until the whole request is done, and the returned value will be all the data. I’d like to be able to display each word (in this case) as it comes in. I suspect there is some built-in chunk size or internal buffering going on. Is there any way to control this?

Filepond cant display image src URL

Filepond is being unable to render images that comes from urls src,it gives an error while trying to display ,i believe it happens because both files and onUpdate files try to manipulate the same state at the same time

Expect to render with consistence