When I try to run my codes like “ts-node index.ts” on visual code studio, it is showing that error messages

/usr/local/lib/node_modules/ts-node/src/index.ts:857
const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
^
TypeError: formatDiagnostics is not a function
at createTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:857:28)
at reportTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:863:19)
at createFromPreloadedConfig (/usr/local/lib/node_modules/ts-node/src/index.ts:874:36)
at phase4 (/usr/local/lib/node_modules/ts-node/src/bin.ts:543:44)
at bootstrap (/usr/local/lib/node_modules/ts-node/src/bin.ts:95:10)
at main (/usr/local/lib/node_modules/ts-node/src/bin.ts:55:10)
at Object. (/usr/local/lib/node_modules/ts-node/src/bin.ts:800:3)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)

And I don’t know how to fix it. Please, help me!!!
My node version is 18.18, typescript version is 5.3.3, ts-node is 10.9.2

Or the issue depends on the versions of languages?

How do I simulate the global variable in Node’s vm module?

I’m trying to use node.js’s vm module for an automated test I’m writing, as far as I can tell, it doesn’t build an environment with the global variable:

$ node -p 'const vm = require("node:vm"); const context = {}; vm.runInNewContext("global.foo=5;", context); console.log(context);'
evalmachine.<anonymous>:1
global.foo=5;
^

ReferenceError: global is not defined

It does seem to come with globalThis, though:

$ node -p 'const vm = require("node:vm"); const context = {}; vm.runInNewContext("globalThis.foo=5;", context); console.log(context);'
{ foo: 5 }
undefined

I’m not sure why or even how it’s missing global, but how do I create a vm context with it?

Note: I’m going to answer my question but I’m not confident it’s a good solution. Let me know if it can be improved.

Is there anyway to make the entire js script delay?

I tried to use async and await but it didn’t work because it runs in the background. I would like a way to make the entire script kinda sleep, like time.sleep in Python.

I tried using async and await with code looking like this:

const sleep = (delayInms) => {
    return new Promise(resolve => setTimeout(resolve, delayInms));
};

async function Delay() {
    console.log("0s");
    await sleep(1000);
    console.log("1s");
}

function main() {
    Delay();
    console.log("1s also")
}

I am working with HTML, CSS and JS. This resulted returning
1s also
in the console at the same time as
0s

Why animation works only from 2nd time [duplicate]

please advise me. Why the property tranzition trigger only from 2 times. In the 1st time the square as if “teleported”. I attach the code

I expected the animation to work the first time around…

h1 {
  text-decoration: underline;
}

.square {
  transition: all 1s ease-out;
  background-color: red;
  width: 2rem;
  height: 2rem;
  position: relative;
}

body {
  box-sizing: border-box;
}

const square = document.querySelector(".square");
const button = document.querySelector(".button");

console.log(window.innerWidth);
let position = 0;

const onClick = (el) => {
  button.disabled = true;

  if (position === 0) {
    el.style.setProperty("left", "calc(100% - 2rem)");
    position = 1;
    setTimeout(() => {
      button.disabled = false;
    }, 1000);
    return;
  }
  el.style.setProperty("left", "0");
  position = 0;
  setTimeout(() => {
    button.disabled = false;
  }, 1000);
  return;
};

button.addEventListener("click", () => {
  onClick(square);
});

JavaScript code does not working on my ASP.NET web form?

Did everything, searched everywhere, thought everytime but now
Tried my best but still can’t handle it. Now running into a problem with a form submit to push data search to controller with javascript code.

I am not getting any error for the JavaScript when attempting to debug in browser. Can someone with more experience with JavaScript show me a better way with the given code?

Here is my code:

Controller:

public IActionResult FindProduct(string keyword)
{
    List<Product> ls = new List<Product>();
    if (string.IsNullOrEmpty(keyword) || keyword.Length < 1)
    {
        return PartialView("ListProductSearchPartial", null);
    }
    ls = _context.Products
        .AsNoTracking()
        .Include(a => a.Cat)
        .Where(x => x.ProductName.Contains(keyword))
        .OrderByDescending(x => x.ProductName)
        .Take(10)
        .ToList();
    if (ls == null)
    {
        return PartialView("ListProductSearchPartial", null);
    }
    else
    {
        return PartialView("ListProductSearchPartial", ls);
    }
}

Form Search in View index:

<form id="formSearch" class="header-searchbox">
    <select class="nice-select select-search-category wide">
        <option value="all">All Category</option>
        <option value="product-item">Product Item</option>
        <option value="product-item-2">Product Item 02</option>
        <option value="product-item-3">Product Item 03</option>
        <option value="product-item-4">Product Item 04</option>
        <option value="product-item-5">Product Item 05</option>
    </select>
    <input id="keyword" class="input-field" type="text" placeholder="Enter Products">
    <button id="btnSearch" class="btn btn-outline-whisper btn-primary-hover" type="submit"><i class="pe-7s-search"></i></button>
</form>

Javascript in View index:

@section Scripts {
    <script>
        $(document).ready(function () {
            var formSP = document.getElementById("formSearch");
            formSP.addEventListener("submit", (e) => {
                $.ajax({
                    url: '@Url.Action("FindProduct", "Search")',
                    datatype: "json",
                    type: "POST",
                    data: { keyword: $('#keyword').val() },
                    async: true,
                    success: function (results) {
                        $('#records_table').html("");
                        $('#records_table').html(results);
                    },
                    error: function (xhr) {
                        alert('error');
                    }
                });
            });
        });
    </script>
}

load image which is filtered

I would like to load the image which is selected in filter. I am not sure how to implement it in javascript. Should I use the attribute for checking if the selected value is matched with the image attributes? I am not sure how to refer to all the attributes of images. What I would like to achieve is that if selected value is equal to the image attributes, the page only show the selected images.

I saw some people use the event listener of DOMContentLoaded. can someone guide me to implement this?

Here is my html script.


    <main>
        
        <!-- filter bar -->
        <div class="filter">
            <label>Filter by Species:
                <select class="species-filter" name="species-filter">
                    <option value="all">All</option>
                    <option value="cat">Cat</option>
                    <option value="dog">Dog</option>
                    <option value="rabbit">Rabbit</option>
                </select>
            </label>
        </div>
        
        <!-- animal photos -->
        <section class="adoption-grid">
            <div class="animal-card" data-species="cat">
                <img src="animal1.jpg" alt="cat">
                <p class="caption">Bailey</p>
            </div>
            <div class="animal-card" data-species="rabbit">
                <img src="animal2.jpg" alt="rabbit">
                <p class="caption">Vince</p>
            </div>
            <!-- Add more animal cards as needed -->
            <div class="animal-card" data-species="turtle">
                <img src="animal3.jpg" alt="turtle">
                <p class="caption">Fifty</p>
            </div>
            <div class="animal-card" data-species="cat">
                <img src="animal4.jpg" alt="cat">
                <p class="caption">Timothy</p>
            </div>
            <div class="animal-card" data-species="cat">
                <img src="animal5.jpg" alt="cat">
                <p class="caption">Matty</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal6.jpg" alt="dog">
                <p class="caption">Bella</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal7.jpg" alt="dog">
                <p class="caption">Nancy</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal8.jpg" alt="dog">
                <p class="caption">Darlie</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal9.jpg" alt="dog">
                <p class="caption">Windie</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal10.jpg" alt="dog">
                <p class="caption">Puff</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal11.jpg" alt="dog">
                <p class="caption">Jelly</p>
            </div>
            <div class="animal-card" data-species="dog">
                <img src="animal12.jpg" alt="dog">
                <p class="caption">Mila</p>
            </div>

            <div class="page-selector">
                <button class="page-button active">1</button>
                <button class="page-button">2</button>
                <button class="page-button">3</button>
            </div>
        </section>
        
    </main>

scrolling the post like Ownmates.com

Scrolling text
I wanted to know whether this was an issue for anyone else. I can only see the code at the top, and it keeps jumping back to the top when I try to scroll down with the middle mouse or by clicking and dragging the slider.

Once I descend past the top, I can no longer see any of the code I’m writing. I’m not sure whether it’s a problem on my end.



Getting Problem while uploading multiple images for specific user in nested array converting it into binary for specific instructorlicense detail

InstructorLiceseDetails is a nested array name in which each object contains LicenseImage with file detail i am unnable to send binary it in formData like how i mentioned in multer

this is how i am sending from frontend  this only receive ProfileImage and TRainerPermitImage 
const InstructorFormData = new FormData();
    let InstructorDataNoImage = {};
for (let [key, value] of Object.entries(InstructorData)) {
    console.log("key:", key, "value:", value);
    if (key.indexOf("Image") > -1) {
       InstructorFormData.append(key, value);
    } else
          InstructorDataNoImage = { ...InstructorDataNoImage, [key]: value };
    }



export const MulterFor_InstructorImages = (req, res, next) => {
    console.log("MulterFor_InstructorImages Reqbody", req.body);
    let MulterVals = {};

    MulterVals.filepath = "./Public/Institute/Instructors";
    MulterVals.UploadFields = [
        { name: "ProfileImage" },
    
        { name: "TrainerPermitImage" },
        ...(req.body.InstructorLicenseDetails || []).map((license, index) => ({
            name: `LicenseImage_${index + 1}`,
        })),
        ...(req.body.SpecialLicenseDetails || []).map((license, index) => ({
            name: `SLicenseImage_${index + 1}`,
        })),
    ];
    MulterVals.filetypes = [];
    MulterVals.filetypes[0] = "image/png";
    MulterVals.filetypes[1] = "image/jpg";
    MulterVals.filetypes[2] = "image/jpeg";
    MulterVals.filetypes[3] = "image/svg+xml";
    MulterMiddleware(req, res, next, MulterVals);

};

now how to send nested array images dynamically field name as i given in multer

How to Calculate Histogram for 32-bit TIFF Image Pixels for Contrast Stretching in JavaScript

I’m working on an image processing application where I need to perform contrast stretching on 32-bit TIFF images using JavaScript. My goal is to calculate the histogram of the image pixels data to determine the appropriate contrast stretching parameters. However, I’m encountering issues with the histogram calculation not producing valid values.

Here’s my current approach:

   function calculateHistogram(pixelData) {
    const binCounts = new Array(256).fill(0);
    pixelData.forEach((pixelValue) => {
    const binIndex = Math.floor(pixelValue / 256); // Assuming 32-bit values are in [0, 
     255]
    binCounts[binIndex]++;
    });
     return binCounts;
   }
  const ContrastStretchedImage = () => {
  const [dataObj, setDataObj] = useState({});
  const [canvasImage, setCanvasImage] = useState(null);
  const [minMaxValue, setMinMaxValue] = useState({ min: 0, max: 0 });
  const plotRef = useRef(null);
  const plotRefForWithoutContrastStretching = useRef(null);
  useEffect(() => {
    axios({
      url: "tiff-image-url",
      method: "GET",
      responseType: "arraybuffer",
    })
      .then(async (response) => {
        const arrayBuffer = await fromArrayBuffer(response.data);
        const image = await arrayBuffer.getImage();
        const pixelsData = await image.readRasters();
        setDataObj({ arrayBuffer, image, pixelsData });
      })
      .catch((error) => error);
  }, []);

  /* useEffect that constantly monitors changes in plot-ref */
  useEffect(() => {
    if (plotRef?.current) {
      plotRef?.current?.render();
      setCanvasImage(plotRef?.current?.canvas);
    }
  }, [plotRef, plotRef?.current?.currentDataset, plotRef?.current?.canvas]);

  const getTiff = useCallback(() => {
    const width = dataObj.image.getWidth();
    const height = dataObj.image.getHeight();
    const histogram = calculateHistogram(dataObj.pixelsData[0]);
    console.log({ histogram });
    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;

    if (plotRef?.current === null) {
      plotRef.current = new plot({
        canvas,
        domain: [36, 60],
        colorScale: "inferno",
      });
      plotRef.current.setData(dataObj?.pixelsData[0], width, height);
    } else {
      plotRef?.current.setData(dataObj?.pixelsData[0], width, height);
    }

    setCanvasImage(canvas);
  }, [dataObj]);

  /* useEffect to updated the domain value of the rendered image */
  useEffect(() => {
    plotRef?.current?.setDomain([30, 60]);
  }, [plotRef]);

  useEffect(() => {
    if (dataObj?.image) {
      getTiff();
    }
  }, [dataObj]);

  return (
    <>
      <div style={{ display: "flex", margin: "2rem" }}>
        <div>
          <Stage width={600} height={600}>
            <Layer>
              <KonvaImage image={canvasImage} width={600} height={600} />
            </Layer>
          </Stage>
        </div>
      </div>
    </>
  );
};

I suspect the issue lies in the calculateHistogram function, especially in how I calculate the binIndex. I understand that 32-bit images have a much larger range of values, but I’m not sure how to adjust my function to accommodate this.

Chrome dynamic content script injection not working when static content script injection works

I have a Manifest V3 chrome extension I’m developing. When I statically display the content scripts in my manifest.json, they are injected into webpages like expected; however, when I shift them into a dynamic injection from a service worker when the extension is installed, it fails to inject the scripts (or even run them) on the page loads. In the service worker, I have asked it to print out all registered content scripts afterwards, and the content scripts do show up as registered.

The manifest.json file without the content_scripts:

{
  "manifest_version": 3,
  "name": "some_name",
  "description": "...",
  "version": "...",
  "action": {
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  },
  "permissions": [
    "scripting",
    "storage"
  ],
  "background": {
    "service_worker": "dist/service_workers/registerContentScripts.js"
  },
  "content_scripts": [
    
  ],
  "web_accessible_resources": [{
    "matches": ["<all_urls>"],
    "resources": ["static/*"]
  }]
}

My src/service_workers/registerContentScripts.ts:

import all_settings from '../default_settings';

const registerContentScripts = async () => {
  if (!(await chrome.storage.session.get('registered')).registered) {
    chrome.storage.session.set({ registered: true });
    const cssScripts = all_settings.sites
      .filter(site => site.css)
      .map(site => {
        chrome.scripting.registerContentScripts([{
          id: site.name.replace(/s/g, '_').toLowerCase() + '_css',
          css: site.css,
          matches: ["<all_urls>"],
          runAt: "document_start"
        }]);
      });

    const removerScript = chrome.scripting.registerContentScripts([{
      id: 'remover',
      js: ['dist/content_scripts/remover.js'],
      matches: all_settings.sites.flatMap(site => site.matches),
      runAt: "document_end"
    }])
      .then(_ => console.log('Registered remover content scripts'))
      .catch(err => console.error('Failed to register remover content scripts', err));

    const replacerScript = chrome.scripting.registerContentScripts([{
      id: 'replacer',
      js: ['dist/content_scripts/replacer.js'],
      matches: all_settings.sites.flatMap(site => site.matches),
      runAt: "document_end"
    }])
      .then(_ => console.log('Registered replacer content scripts'))
      .catch(err => console.error('Failed to register replacer content scripts', err));
    
    await Promise.all([...cssScripts, removerScript, replacerScript])
      .then(_ => console.log('Registered content scripts'))
      .catch(err => console.error('Failed to register content scripts', err));
  }
};

chrome.runtime.onInstalled.addListener(
  () => registerContentScripts().then(
    _ => chrome.scripting.getRegisteredContentScripts().then(
      scripts => console.log(scripts)
    )
  )
);

chrome.webNavigation.onBeforeNavigate.addListener(registerContentScripts);

Sample of one of the content script outputs:

[
    {
        "allFrames": false,
        "css": [
            "static/css/injected_css/google.css"
        ],
        "id": "imperial_website_css",
        "matchOriginAsFallback": false,
        "matches": [
            "https://*.google.com/*"
        ],
        "persistAcrossSessions": true,
        "runAt": "document_start"
    },
    ...
]

For this particular project, registering content scripts dynamically is quite a bit more preferable than statically, as I hope to add a lot of settings-based interactivity eventually, so going back to static injection is not a great option. Again, I have tried copying the content scripts I get from the console output back into my manifest.json, and it works perfectly. I’m not getting any errors on either the service worker nor the webpage’s web console (from the DevTools panel on the webpage, the content script does not even show up, and some logging at the start of that content script also does not show up, so it is entirely not being loaded).

webRTC connection creating in firefox only , other browsers are not creating

All I learing the webRTC. To prectis webRTC I create one project in php. Use the webSoteck for signaling. In this project only webRTC connection will establish and text message will send to p2p to verify the connection.

When I test it in firefox it work well, p2p connection is establish and getting the message also. But when I check it in chrome,Brave and opera the p2p connection is not establish.

I check the SDP, In firefox SDP length is more then other browsers SDP. I think it is ICE that not creating.

To verify it I add the “onicecandidate” to listion the events of the ice and when I run it all browsers and logs got only in firefox.

What i am missing can you help to solve it ?

This is my JS file.


const sender = "sender";
const receiver = "receiver";
let code = 0;
const stun_server = {
iceServers: [
{
urls: ['stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19302'],
}
],
iceCandidatePoolSize: 10,
}

let pc = new RTCPeerConnection(stun_server);

pc.onicecandidate = event => {
console.log('ICE candidate Event trigger :',event.candidate);
}

function startWebSocket(role){
try {
console.log(role);
socket = new WebSocket("ws://127.0.0.1:8080");

        var socketOpen = (e) => {
            console.log("socket connect successfully...");
            startWebRTC(role);
        }
    
        var socketMessage = (e) => {
            console.log(`Message from socket... : ${e.data}`);
            
            let response = JSON.parse(e.data);
            let offer_or_answer = response.ICE;
            if(response.role == "sender") {
                createAnswer(offer_or_answer);                
            } else if(response.role == "receiver") {
                handleAnswer(offer_or_answer);
            }
        }
    
        var socketClose = (e) => {
            console.log(`socket Closed...`);
            socket.close();
        }
    
        var socketError = (e) => {
            console.error(`socket Error : ${e.data}`);
        }
        
    
        socket.addEventListener("open",socketOpen);
        socket.addEventListener("message", socketMessage);
        socket.addEventListener("close", socketClose);
        socket.addEventListener("error", socketError);
    
    
    } catch(error) {
        showCatchError('startWebSocket : unable to connect with server : ',error);
    }

}

function startWebRTC(role) {
try {

        console.log('webRTC Start......');
        if(role == sender) {
            createTheOffer(role);
        } else if(role == receiver) {
            if(code.trim() === '') {
                alert('Please enter Connection Code');
                return false;
            }
            inquiryByCode(code, role);
        };
    
        createChannel();
        
    } catch(error) {
        showCatchError('startWebRTC : unable to start webRTC : ',error);
    }

}

function createTheOffer(role) {
try {

        pc.createOffer().then(offer => pc.setLocalDescription(offer)).then(() => {
            console.log(`the SDP start for ${role}.......`);
    
            if(role == 'sender'){
                code = Math.floor(Math.random() * 9000) + 1000;
                alert(`Connection Code : ${code}` );
                
            } else if(role == 'receiver') {
                code = document.querySelector('#connection_code').value;
                if(code.trim() === '') {
                    alert('Please enter Connection Code');
                    return false;
                }
            }
            
            let Msg = {
                    role: role,
                    code: code,
                    type: 'connection',
                    ICE: pc.localDescription
                };
    
            sendMessageToServer(Msg);
        });
        createChannel();
    
    } catch(error) {
        showCatchError('createTheOffer : unable to create offer : ',error);
    }

}

async function createAnswer(offer) {
console.log('Send Answer.....');
await pc.setRemoteDescription(offer);
pc.createAnswer().then(answer => {

        pc.setLocalDescription(answer);
        console.log(`answer: ${answer}`);
        let Msg = {
            role: 'receiver',
            code: code,
            type: 'answer',
            ICE: answer
        };
    
        sendMessageToServer(Msg);
    });

}

async function handleAnswer(answer) {
console.log(`Handle Answer.....${answer}`);
await pc.setRemoteDescription(new RTCSessionDescription(answer));
}

function inquiryByCode(code, role){
try {

        let Msg = {
            role: role,
            code: code,
            type: 'connection',
            ICE: pc.localDescription
        };
        sendMessageToServer(Msg);
    
    } catch(error) {
        showCatchError('inquiryByCode : unable to send inquiry : ',error);   
    }

}

function createChannel() {

    try {
         
        const dataChannel = pc.createDataChannel('textChannel');
        console.log('DATA CHANNEl START');
        
        dataChannel.onopen = () => {
            console.log('Data channel opened');
            document.querySelector('#send_button').addEventListener('click', function() {
                let user_message = document.querySelector('#send_message').value;
                sendMessage(user_message);
            });
        };
        
        dataChannel.onerror = function(error) {
            console.log('DATA CHANNEl ERROR : ',error);
            showCatchError("Data channel error :",error);
            // Handle the error here
        };
    
        // Receiver side
        pc.ondatachannel = (event) => {
            const dataChannel = event.channel;
            
            dataChannel.onmessage = (event) => {
                console.log('Received message:', event.data);
                // Handle the received message
            };
        };
        
        // Sending text message from sender to receiver
        function sendMessage(message) {
            if (dataChannel.readyState === 'open') {
                dataChannel.send(message);
                console.log('Message sent:', message);
            } else {
                console.error('Data channel not open');
            }
        }
    
    } catch(error) {
        showCatchError('createChannel : unable to create channel : ',error);
    }

}

    function sendMessageToServer(Msg) {
            try {
                socket.send(JSON.stringify(Msg));
            } catch(error) {
                showCatchError('sendMessageToServer : unable to send : ',error);
        }
    }

function checkPeerConnectionState() {
console.log(`Configuration :`,pc);
console.log(`ICE connection state `, pc.iceConnectionState);
}

function showCatchError(msg, error){
console.error(msg, error.message);
}

How to open a deeplink without creating a new tab or window in a web extension

I have an anchor tag which when selected should open a link to an external application (Obsidian). Here’s an example link: obsidian://action?param1=value&param2=value.

I expect that clicking on the anchor opens the external application without creating windows or tabs.

Current Browsers:

  • Firefox
  • Chrome

Current Permissions:

  • tabs
  • storage

I’m trying to avoid hosts_permissions if possible.

Several tried methods:

In the below examples, my usage of the “browser” namespace is equivalent to the chrome namespace.

  • selecting anchor href
    • this opens confirmation window inside popup which cuts off the confirmation since my popup is smaller in size
  • window.open()
    • This opens a new tab which closes when the open button on the prompt window is selected. If the prompt is closed, an empty tab remains
  • browser.scripting.executeScript
    • This requires the scripting permission which is fine, but opening a URL inside an injected script requires declared access to the tab URL (hosts_permissions in my case)
  • window.open(message.value, ‘_self’) within content_script
    • This works perfectly, except it requires the content_script and I need to match all URLs. Since I want to avoid hosts_permissions, this is not suitable
  • browser.tabs.create()
    • Same behavior as window.open()

Maybe there is another way or something I didn’t think of like being able to resize the prompt window?

Can I pass parameter other than Payload to NGXS action?

I am trying to have a Ngxs action that takes a parameter along with Payload. I use this parameter to decide if I need to send a notification or not.

@Action(UpdateUser)
  async UpdateUser(
    ctx: StateContext<ProfileStateModel>,
    userProfile: User,
    notify: boolean
  ): Promise<void> {
      await this.updateProfileSvc(userProfile){
         .subscribe({
             next: (data: User) => {
                 ctx.setState({...state, sendNotification: notify});
              }
           })
     }
 }

User is the payload in this Action. When I pass the second parameter “notify” with value “true/false”, I always receive it as undefined.

How to have a parameter other than payload in the Ngxs action?

I tried to print the value of notify in the console, and I see it “undefined” always.

Please share your inputs here/ Thanks.

Streaming video Chunks to from backend

I want to record the video of the webcam. So, I am using mediaDevices.getUserMedia and taking chunks for every 30sec and sending them to the python backend through the socket. this backend intern uploads the chunks to s3 using multi-part uploading. However, there is some issue with the format incompatibility. Can some one help me with this?I think there is some compatibility issue

const mimeType = 'video/webm; codecs="vp8, opus"';
mediaStream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });
            if (mediaStream) {
                mediaRecorder.current = new MediaRecorder(mediaStream, { type: mimeType });
                mediaRecorder.current.start(30000);
                mediaRecorder.current.ondataavailable = (event) => {
                    if (typeof event.data === "undefined") return;
                    if (event.data.size === 0) return;
                    const customData = {chunk:event.data, custom_data: 'tarun' };
                    sendDataToServer('video_stream', customData);
                };

******************************
@socketio.on('start_stream')
def start_stream(data):
    global MULTIPART_UPLOAD_ID
    custom_data = data.get('custom_data')
    print('Start streaming action received with custom data:', custom_data)
    # Start multi-part upload
    response = s3.create_multipart_upload(Bucket=BUCKET_NAME, Key=f'{custom_data}.webm', ContentType='video/webm')
    MULTIPART_UPLOAD_ID = response['UploadId']
    print('Multi-part upload started:', MULTIPART_UPLOAD_ID)


@socketio.on('end_stream')
def end_stream(data):
    global MULTIPART_UPLOAD_ID, PART_NUMBER, PARTS
    custom_data = data.get('custom_data')
    print('End streaming action received with custom data:', custom_data)
    # Complete multi-part upload
    parts = [{'ETag': part['ETag'], 'PartNumber': part['PartNumber']} for part in PARTS]
    response = s3.complete_multipart_upload(
        Bucket=BUCKET_NAME,
        Key=f'{custom_data}.webm',
        MultipartUpload={'Parts': parts},
        UploadId=MULTIPART_UPLOAD_ID
    )
    print('Multi-part upload completed:', response)
    # Reset variables
    MULTIPART_UPLOAD_ID = None
    PART_NUMBER = 1
    PARTS = []


@socketio.on('video_stream')
def video_stream(data):
    global PART_NUMBER, PARTS
    chunk = data.get('chunk')
    custom_data = data.get('custom_data')
    print('Received video chunk with custom data:', custom_data, ', Length:', len(chunk), 'bytes')
    # Upload chunk to multi-part upload
    print(BUCKET_NAME)
    print()
    response = s3.upload_part(
        Bucket=BUCKET_NAME,
        Key=f'{custom_data}.webm',
        PartNumber=PART_NUMBER,
        UploadId=MULTIPART_UPLOAD_ID,
        Body=chunk
    )
    print('Uploaded part:', PART_NUMBER)
    PARTS.append({'PartNumber': PART_NUMBER, 'ETag': response['ETag']})
    PART_NUMBER += 1

Error from web and python

websocket.js:54 WebSocket connection to 'ws://localhost:5004/socket.io/?EIO=4&transport=websocket&sid=Ymb7eOcaud_yV-rJAAAG' failed: Invalid frame header

botocore.exceptions.ClientError: An error occurred (MalformedXML) when calling the CompleteMultipartUpload operation: The XML you provided was not well-formed or did not validate against our published schema