No cookie in request headers from tRPC client received at tRPC server

I try to get cookies of the request from tRPC client using this context.ts of tRPC server:

import { IncomingMessage, ServerResponse } from 'http';
export async function createContext({ req, res }: { req: IncomingMessage; res: ServerResponse }) {

    console.log(req.headers);
    
    le user = null;
    return {
        user,
    };
}
export type Context = Awaited<ReturnType<typeof createContext>>;

tRPC server is hosted under http://localhost:2022

and I send requests to it from tRPC client at http://localhost:3000 like

import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
const trpcClient = createTRPCProxyClient<AppRouter>({
    links: [
        httpBatchLink({
            url: 'http://localhost:2022',
            fetch(url, options) {
                return fetch(url, {
                  ...options,
                  credentials: 'include',
                });
            },
        }),
    ],
});
export default trpcClient;

and there are cookies with HttpOnly and SameSite=Lax at http://localhost:3000, but they are not sent to tRPC server as I don’t see any cookie in headers in console.log(req.headers), what I see is only

{
  host: 'localhost:2022',
  connection: 'keep-alive',
  'content-type': 'application/json',
  accept: '*/*',
  'accept-language': '*',
  'sec-fetch-mode': 'cors',
  'user-agent': 'node',
  'accept-encoding': 'gzip, deflate'
}

I use standalone tRPC server with working cors like

createHTTPServer({
    middleware: cors({
        origin: 'http://localhost:3000',
        credentials: true
    }),
    router: appRouter,
    createContext,
}).listen(2022);

when I go at http://localhost:2022 in browser, I see the cookies

how to receive cookies at the tRPC server?

JavaScript replaceAll Regex Matches with translated character Code

I want to use the regex capture group to translate UTF-16 values in an ID.

var x = "ELEMENTT_x5F_GS1_x5F_MARKETING_x5F_CLAIM__x3B__INSTANCE_x3D_3__x3B__LOCALE_x3D_1_"
var regex = /_(x..)_/g;
var replacedID = x.replaceAll(regex, String.fromCodePoint("0" + "$1"));

however this does not appear to fill in the captured value into the string the same way it normally works.
i have tried any which way and it does not seem to recognize the “$1” as replace capture group.

Show/hide one element at the time

I using this script to show/hide content. However, how can I close open elements when opening one?
I tried with something like this, but it’s not working correctly:

// Get siblings
var contentSiblings = document.querySelectorAll('.content');

// close them before opening new one
if (contentSiblings) {
        contentSiblings.forEach((elem) => {
                if (elem.classList.contains('is-visible')) {
                        hide(elem);
                }
        });
}

// Show/hide filter content
var show = function (elem) {
    elem.classList.add('is-visible');
};

// Hide an element
var hide = function (elem) {
    elem.classList.remove('is-visible');
};

// Toggle element visibility
var toggle = function (elem) {

    // If the element is visible, hide it
    if (elem.classList.contains('is-visible')) {
        hide(elem);
        return;
    }

    // Otherwise, show it
    show(elem);
};

// Listen for click events
document.addEventListener('click', function (event) {

    // Make sure clicked element is our toggle
    if (!event.target.classList.contains('btn')) return;

    // Prevent default link behavior
    event.preventDefault();

    // Get the selected content
    var content = document.querySelector(event.target.hash);
    if (!content) return;

    // Toggle the content
    toggle(content);

}, false);
.content {
    display: none;
    opacity: 0;
    transition: opacity .15s linear;
}

.content.is-visible {
    display: block;
    opacity: 1;
}
<a class="btn" id="btn-one" href="#one">Button one</a>
<a class="btn" id="btn-two" href="#two">Button two</a>
<div class="content" id="one">Content one</div>
<div class="content" id="two">Content two</div>

How to improve page speed

I’m running an e-commerce site, FominSoap.com, which is built on WooCommerce. The site has numerous product pages, each with several high-quality images. While the images are essential for showcasing our products, they’re significantly affecting the page load speed.

I have installed wp rocket and light speed cache to optimize speed but I am unable to improve it

In JavaScript, how to find Strong number & Perfect number? [closed]

In JavaScript, how to find Strong number & Perfect number?
Some foundational questions:
how do we extract digits in Javascript using while loop?

How do we find out STRONG NUMBERS or not using while loop?

What is a nested while loop?

thank you

Definition: Strong numbers are the sum of factorials are same as the original number(eg.145)
Perfect numbers are the sum of the proper divisors make the sum(eg.28)

About Strong numbers, the steps are:

  1. Extract digits
  2. Factorials
  3. Sum up the factorials
  4. Check whether the sum is the same as the original number

Need to know the programming.

thx

Streaming chunks of video using javascript

Using JavaScript I am trying to receive chunks of video and display them in a html video tag. but in the code I have, after displaying 3 or 4 chunks, it gets stuck and doesn’t move to the next chunk.
can you help me with this?


// Fetch an encrypted video chunk from the server
async function fetchChunk(chunkIndex) {
    const url = `http://localhost/video/encrypted_chunks/chunk_${chunkIndex}.enc`;
    try {
        const response = await fetch(url);
        if (response.ok) {
            return await response.arrayBuffer();
        } else {
            console.error(`Failed to fetch chunk ${chunkIndex}: Status ${response.status}`);
            return null;
        }
    } catch (error) {
        console.error(`Error fetching chunk ${chunkIndex}:`, error);
        return null;
    }
}

function appendBuffer(sourceBuffer, decryptedData) {
    return new Promise((resolve, reject) => {
        function onUpdateEnd() {
            sourceBuffer.removeEventListener('updateend', onUpdateEnd);
            resolve();
        }

        if (sourceBuffer.updating) {
            sourceBuffer.addEventListener('updateend', onUpdateEnd, { once: true });
        } else {
            sourceBuffer.appendBuffer(new Uint8Array(decryptedData));
            resolve();
        }
    });
}

// Finalize the MediaSource stream
function finalizeStream(mediaSource) {
    if (mediaSource.readyState === 'open') {
        mediaSource.endOfStream();
    }
}

// Main function to handle video streaming
async function streamVideo() {
    const mediaSource = new MediaSource();
    const video = document.getElementById('videoPlayer');
    video.src = URL.createObjectURL(mediaSource);

    mediaSource.addEventListener('sourceopen', async () => {
        const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8, vorbis"');
        let chunkIndex = 1;

        const filename = 'sample-2.webm'; // Replace with the actual filename
        const { key, iv } = await calculateKeyIv(filename);

        // Function to handle fetching, decrypting, and appending chunks
        async function handleChunks() {
            try {
                while (true) {
                    if (sourceBuffer.updating) {
                        await new Promise(resolve => sourceBuffer.addEventListener('updateend', resolve, { once: true }));
                    }

                    const encryptedData = await fetchChunk(chunkIndex);
                    if (!encryptedData) break; // No more data

                    const decryptedData = await decryptChunk(encryptedData, key, iv);
                    await appendBuffer(sourceBuffer, decryptedData);

                    chunkIndex++;
                }

                // Wait for buffer to be done updating before finalizing
                if (!sourceBuffer.updating) {
                    finalizeStream(mediaSource);
                    createWatermark();
                }
            } catch (error) {
                console.error('Error processing chunks:', error);
            }
        }

        // Start processing chunks
        handleChunks();
    });
}

// Call the streamVideo function to start streaming
streamVideo();

I think the problem is probably with the buffer but I’m new to JavaScript and I haven’t been able to debug it!

We are using JavaScript constructor class to set data attribute values for ajax call

Below is the code snippet

”’

var FilterTest = class { 
constructor() { 
  this.data_scope= $("#ID").data('scope');
}; 
getAttrs() { 
 var Opts = {data_scope: this.data_scope};
 Opts['attr2'] = "ABC";
 return Opts;
 }  
}

Obj = new FilterTest();

$.ajax({
 url: URL,
 data: Obj.getAttrs(),
 dataType: 'json'
}).done

on live site that opts return empty hash in ajax call. This issue comes for some users

Constructor class return empty hash in some browsers

How to prevent wp_localize_script from localize the ajax URL in the array?

Currently in my WordPress plugin, I use wp_localize_script to pass data from PHP to JS, as below:

    wp_localize_script($this->plugin_name, 'MyObj', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));

It works properly in English post with a shortcode of the plugin. However, in the Chinese post with the same shortcode, it does not. After tracing the data, I find in the Chinese post, the ajax_url will be added a language slug.

For example, if the English post is https://www.example.com/blogs/jpg-to-png/, then the ajax_url will be https://www.example.com/blogs/wp-admin/admin-ajax.php, which is correct.

But in the Chinese version, https://www.example.com/zh-CN/blogs/jpg-to-png/, then ajax_url will also be changed to https://www.example.com/zh-CN/blogs/wp-admin/admin-ajax.php, which is not desired.

How to prevent this? I try to pass the root_url, admin_url, but wp_localize_script will always add the language slug for the Chinese post. How to keep the data intact when passing it from PHP to JS?

How to ensure an isolated testing environment if the call to the tested class is in the same file as the class body?

I would like to write unit tests (JavaScript, Jest) for my class, but I don’t understand something. When writing a test, I need to import a class file into the test. But import calls the entire file. So, if I had a class call with the original data in the imported file, the class with the original data would be called first, and next with the test data.

  1. Does this mean my class is not well isolated for test?
  2. Shouldn’t I create a class instance in the same file as the class body? I haven’t found any contraindications anywhere, but maybe it’s bad from an architectural point of view?
  3. Is there a way to get around this, but I just haven’t found it yet?

Sample class:

class ABC {
    constructor(settings) {
        this.a = settings.a
        this.b = settings.b
        this.logText = settings.logText

        this.sum(this.a, this.b, this.logText)
    }

    sum() {
        console.log("log text:", this.logText)
        return this.a + this.b
    }
}

//Simplified settings. Originally it contains, for example: an 
//asynchronous method for calling endpoint.
let settingsArray = [{
    a: 1,
    b: 1,
    logText: "original"
}]

function createInstance () {
    for(let setting from settingsArray) {
      new ABC(setting);
    }
}
createInstance(settingsArray)

Specifically about the problem to understand:

  1. in the test I import a class ABC
  2. the class is called, the createInstance method creates instances of the class with the original data (settingsArray). I can see log “log text: original”. I think, in correctly done test I shouldn’t see it, because in my test settingsArray is overwritten and logText != “original”.
  3. I’m just taking the test now
  4. in the test, I have overwritten settingsArray where for example: logText: “from test”
  5. only now I am seeing an instance of the class with test data
  6. even if the test passes, if the original settings contain e.g. external methods, errors are returned along the way (or later, if there were e.g. asynchronous methods). And I guess it shouldn’t be like that.

Can someone help me understand what should be good and what is wrong with my way of thinking? Maybe this is no problem, and I don’t understand correctly what is isolation for unit test?

NextJS folder structure [closed]

I just started learning NextJS and im already confused with the folders and file structure.
Did some research on the web to see if there is a best practice, but couldnt find anything concrete.

Anyways, below is my project overview.
I’m bulding a simple one page website, with the following sections:
About me, services, projects, skills, etc.
This ones i divided them and place them in the components folder that I created.

I will also have a navbar, and a footer.

Now the problem I am having.
When I created the project with the create next app, there are the following files and folders:
In src/app there are layout and page files.

So, my components should go to page file, and the navbar component should go to layout file?

I saw in similar projects some people that did the following:
they got rid of the app directory and the layout and page file.
And went it src/pages/_app.tsx. And in the pages directory were other files(index, about, inquiry).

I want to know if there is best practice for this, and which one of the above case is write.
What way should i go?

Using nextjs 14.

Higcharts annotations for Wordcloud and Dependency wheel

I’m trying to add annotations for Highcharts charts, and I’m having trouble with Wordcloud and Dependency wheel. API docs states that annotations could be specified via the point ID, so I tried to do that, but Wordcloud display the annotation in the top left corner, and Dependency wheel just does not display anything.

Do you have any idea on how to resolve this?

I created a JSfiddle based on the Higcharts demo for those

Wordcloud: https://jsfiddle.net/eqLrz70o/1/

const text =
        'Chapter 1. Down the Rabbit-Hole ' +
        'Alice was beginning to get very tired of sitting by her sister on ' +
        'the bank, and of having nothing to do: ' +
        'once or twice she had peeped into the book her sister was reading, ' +
        'but it had no pictures or conversations ' +
        'in it, 'and what is the use of a book,' thought Alice ' +
        ''without pictures or conversation?'' +
        'So she was considering in her own mind (as well as she could, for ' +
        'the hot day made her feel very sleepy ' +
        'and stupid), whether the pleasure of making a daisy-chain would be ' +
        'worth the trouble of getting up and picking ' +
        'the daisies, when suddenly a White Rabbit with pink eyes ran close ' +
        'by her.',
    lines = text.replace(/[():'?0-9]+/g, '').split(/[,. ]+/g),
    data = lines.reduce((arr, word) => {
        let obj = Highcharts.find(arr, obj => obj.name === word);
        if (obj) {
            obj.weight += 1;
        } else {
            obj = {
                    id: word,
                name: word,
                weight: 1
            };
            arr.push(obj);
        }
        return arr;
    }, []);

Highcharts.chart('container', {
    accessibility: {
        screenReaderSection: {
            beforeChartFormat: '<h5>{chartTitle}</h5>' +
                '<div>{chartSubtitle}</div>' +
                '<div>{chartLongdesc}</div>' +
                '<div>{viewTableButton}</div>'
        }
    },
    series: [{
        type: 'wordcloud',
        data,
        name: 'Occurrences'
    }],
    annotations: [{
        labels: [{
        point: 'the',
        text: 'POINT BY ID'
      },
      {
        point: {x:100, y:100},
        text: 'POINT BY PX'
      }]
    }],
    title: {
        text: 'Wordcloud of Alice's Adventures in Wonderland',
        align: 'left'
    },
    subtitle: {
        text: 'An excerpt from chapter 1: Down the Rabbit-Hole',
        align: 'left'
    },
    tooltip: {
        headerFormat: '<span style="font-size: 16px"><b>{point.key}</b>' +
            '</span><br>'
    }
});

Dependency wheel: https://jsfiddle.net/h0zd4jwk/

Highcharts.chart('container', {

    title: {
        text: 'Highcharts Dependency Wheel'
    },

    accessibility: {
        point: {
            valueDescriptionFormat: '{index}. From {point.from} to ' +
                '{point.to}: {point.weight}.'
        }
    },
    
    annotations: [{
        labels: [{
        point: {x: 200, y: 200},
        text: 'Point by PX'
      },{
        point: 'brazil-france',
        text: 'Point by ID'
      }]
    }],

    series: [{
        keys: ['from', 'to', 'weight', 'id'],
        data: [
            ['Brazil', 'Portugal', 5],
            ['Brazil', 'France', 1, 'brazil-france'],
            ['Brazil', 'Spain', 1],
            ['Brazil', 'England', 1],
            ['Canada', 'Portugal', 1],
            ['Canada', 'France', 5],
            ['Canada', 'England', 1],
            ['Mexico', 'Portugal', 1],
            ['Mexico', 'France', 1],
            ['Mexico', 'Spain', 5],
            ['Mexico', 'England', 1],
            ['USA', 'Portugal', 1],
            ['USA', 'France', 1],
            ['USA', 'Spain', 1],
            ['USA', 'England', 5],
            ['Portugal', 'Angola', 2],
            ['Portugal', 'Senegal', 1],
            ['Portugal', 'Morocco', 1],
            ['Portugal', 'South Africa', 3],
            ['France', 'Angola', 1],
            ['France', 'Senegal', 3],
            ['France', 'Mali', 3],
            ['France', 'Morocco', 3],
            ['France', 'South Africa', 1],
            ['Spain', 'Senegal', 1],
            ['Spain', 'Morocco', 3],
            ['Spain', 'South Africa', 1],
            ['England', 'Angola', 1],
            ['England', 'Senegal', 1],
            ['England', 'Morocco', 2],
            ['England', 'South Africa', 7],
            ['South Africa', 'China', 5],
            ['South Africa', 'India', 1],
            ['South Africa', 'Japan', 3],
            ['Angola', 'China', 5],
            ['Angola', 'India', 1],
            ['Angola', 'Japan', 3],
            ['Senegal', 'China', 5],
            ['Senegal', 'India', 1],
            ['Senegal', 'Japan', 3],
            ['Mali', 'China', 5],
            ['Mali', 'India', 1],
            ['Mali', 'Japan', 3],
            ['Morocco', 'China', 5],
            ['Morocco', 'India', 1],
            ['Morocco', 'Japan', 3],
            ['Japan', 'Brazil', 1]
        ],
        type: 'dependencywheel',
        name: 'Dependency wheel series',
        dataLabels: {
            color: '#333',
            style: {
                textOutline: 'none'
            },
            textPath: {
                enabled: true
            },
            distance: 10
        },
        size: '95%'
    }]

});

Why is assigning a function to window in a module not working?

module.mjs

console.log('module1 loaded');

window.module1_function = () => {
   console.log('module1_function executed');
   return 42;
}

index.html

<script defer type="module" src="./js/module1.mjs"></script>

<script defer>
   module1_function();
</script>

Output

Uncaught ReferenceError: module1_function is not defined

module1 loaded

As you can see it fails. When called the function is not defined. The module is not loaded until after the function is called. Executing module1_function() in the console the function runs successfully.

Why?

defer should cause the inline script to not be processed until after module.mjs has executed, at which point the function should be assigned and available.

How do I make the function in this module available for use in a script? I do not want to have to turn my script into a module and import the function.

Why use const when getting a random element in array? [closed]

I see a lot of people using the keyword ‘const’ instead of ‘let’ when storing the random value you get from an array. is this a preference or a convention?

arrWords = ["Soothing", "Humid", "Cold", "Ashes"];
let usersNameInput = prompt("Enter name: ");
let randomValueFromArrWords = Math.floor(Math.random() * arrWords.length);
console.log( usersNameInput + " You are probably " + arrWords[randomValueFromArrWords]);

Well above, is some sordid piece of JavaScript code and it works so I’m wondering why on a lot of answers for storing the random value, it’s always a const?

Why youtube don’t need user to interact first with document for playing a video? [duplicate]

I am creating a VOD website, and when working on the deep url functionality (url that point directly a video ex: mysite.com/watch/abcd) i have this error in console (Chrome):

videoplayer.js:149 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://developer.chrome.com/blog/autoplay

I completly understand the problem, but how does youtube make it work?
When you open a direct link, the video launch itself: https://www.youtube.com/watch?v=dQw4w9WgXcQ

(I tried with autoplay but same error)

Why data entered in previous textfields is vanishing (page is refreshing) even though the onClick event is set on a non-submit button? [duplicate]

I have setup a webpage with two input fields (type number) and a button.

The button has an onClick event setup which is a function that picks values from the input fields and creates a label inside the same fieldset to declare that a Player (input value) has entered round (input value).

That’s all it does.

But I am amazed when I click the button. I see that the label declaring the announcement appears without any problem, but at the same time, the numbers contained in the input fields vanish immediately. I suspect that the page is refreshing. But then again, the button setup with onClick event is not a ‘Submit’ type of button. It’s just a button.

What is happening here? I want to create that announcement label at the click of the button but keep all the numbers entered in the previous input fields.

Interestingly, if you take the button out of the fieldset and use a new fieldset below it to append the label, then the data entered in the previous input fields does not vanish!!.

I know about event bubbling. But in my code the onClick event is the only event setup to fire and no other. Please let me know what is happening here. My code is as shown below –

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vanila JavaScript</title>    
</head>
<body>
        <h1>Welcome to Dynamic Forms</h1>
        <h2>(for practicing JavaScript)</h2>
        <hr />
        <p>Your practice begins now...</p>
        
        <form id="frm1" action="" method="">
            <fieldset id="fldset_1">
                <legend>Fieldset One</legend>
                <label style="width: 200px; background-color: teal; color: white;">Enter Player Number:</label>
                <input id="noOfPlayers" type="number" style="width: 50px;">
                <br>
                <label style="width: 200px; background-color: teal; color: white;">Enter Round Number:</label>
                <input id="noOfRounds" type="number" style="width: 50px;">
                <br>
                <button type="button" style="width:150px; height: 50px; background-color: black; color: yellow;" onclick="createNxtRound()">Create Next Round</button>    
                <br>
            </fieldset>
            
            <fieldset id="fldset_2">
                <legend>Fieldset Two</legend>

            </fieldset>
        </form>
        <script>
            function createNxtRound()
            {
                const fieldset = document.getElementById("fldset_1");
                const lbl = document.createElement("label");
                lbl.setAttribute("style", "width:100%; background-color:yellow; color:black; font-weight:bold");
                lbl.innerHTML = "Player " + document.getElementById("noOfPlayers").value + " has entered round " + document.getElementById("noOfRounds").value
                fieldset.appendChild(lbl);                
                fieldset.innerHTML += "<br />";
            }
        </script>
    </body>
</html>