useContext wrap throw error even the components is wrapped [React Native]

i wrap all of my components and screen inside the CartProvide but its still show “useCart must be used within a CartProvider”

I wanna show the receipt of the total orders but it show the error

below is my code for CartContext

type CartItem = {
  name: string;
  price: number;
  imageUrl: any;
  type: "FOOD" | "DRINK";
};

interface CartContextType {
  orders: CartItem[];
  addToCart: (item: CartItem) => void;
  clearCart: () => void;
}

const CartContext = createContext<CartContextType | undefined>(undefined);

export const CartProvider = ({ children }: { children: React.ReactNode }) => {
  const [orders, setOrders] = useState<CartItem[]>([]);

  const addToCart = (item: CartItem) => {
    setOrders((prevOrders) => [...prevOrders, item]);
  };

  const clearCart = () => {
    setOrders([]);
  };

  return (
    <CartContext.Provider value={{ orders, addToCart, clearCart }}>
      {children}
    </CartContext.Provider>
  );
};

export const useCart = () => {
  const context = useContext(CartContext);
  if (!context) {
    throw new Error("useCart must be used within a CartProvider");
  }
  return context;
};

my index

const index = () => {
  return (
    <CartProvider>
      <View style={{ flex: 1 }}>
        <Greet />
        <Menu />
      </View>
    </CartProvider>
  );
};

and my Cart screen

const Cart = () => {
  const { orders } = useCart(); // Fetch cart orders

  
  const total = orders.reduce((sum, item) => sum + item.price, 0);

  return (
    <CartProvider>
      <ScrollView>
        <Header />
        <CartComp
          itemPrices={orders.map((item) => item.price)}
          menus={orders.map((item) => item.name)}
          total={total}
        />
      </ScrollView>
    </CartProvider>
  );
};

i already wrap all of that inside of CartProvider but it still show the error, how this could happen?

How to maintain scroll position when moving element

I have an element (container) with horizontal scroll. For example:

<div class="rows">
  <div class="row"></div>
  <div class="row"></div>
  <div class="row"></div>
  <div class="row">
    <div id="container"></div>
  </div>
  <div class="row"></div>
  <div class="row"></div>
  <div class="row"></div>
  <div class="row"></div>
  <div class="row"></div>
</div>

If you move the element to another row, it will reset the horizontal scroll in the container. Why is that? How can I maintain the scroll position? Is it possible to fix with only CSS?

Here’s a demo:
https://jsbin.com/gugotewane/2/edit?html,css,js,output

Chromium C++ assert warning in JavaScript code

WebGPU C++ warning

I get a console warning in unrelated JS code.

Ignoring the warning, all JS code continues to run without any apparent problems, however I do not want this to appear in the console.

My question is

Is there a work around that stops the warning from appearing in the console?

Details

Chrome Version 129.0.6668.71 (Official Build) (64-bit)

JavaScript source code and line numbers when warning appears

164        createAtlas() {
165            if (this.sprites) {
166                const atlas = new Uint32Array(this.sprites.length * 2);
                                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~!
  • Note That the warning appears when I step over line 165, but line 166 has not yet been executed.

  • Note All created textures up to this point have CopyDst set and only textures that (are/will) be rendered to have RenderAttachment usage flags set.

  • Note The warning can not be caught via a try catch.

Warning as copied from console.

SpriteSheets.js:166 Destination texture needs to have CopyDst and RenderAttachment usage.
    at APIInjectError2 (....third_partydawnsrcdawnnativeDevice.cpp:2023)
        createAtlas @       SpriteSheets.js:166
        buildAllSprites @   batchSprites.js:34
        await in buildAllSprites        
        main @              webGPUTest2.js:73
        await in main       
        (anonymous) @       webGPUTest2.js:26

how to get three.js crossFadeTo() working

So I’ve downloaded a mixamo character and, separately, an animation pack. I’ve set up a scene with lights, cameras, textured ground and all. I load all the animations and then, I play one of the animations. I setup an eventListener to tell me when the animation ends (All this is working!) THEN I attempt to crossFadeTo a random endAction. HERE the character fades to its tpose (this is not what I want). Here is the relevant code:

    loadAnimations(){
        const loader = new FBXLoader();
        var that = this;
        for(var i=0;i<this.animationFiles.length;i++){
            loader.load(that.animationFiles[i],
                function(animObj){
                    that.animations.push(animObj.animations[0]);
                },
                function(){
                    console.log(Math.round(100*((that.animations.length+1)/that.animationFiles.length))+'% loaded');
                    if((that.animations.length+1)==that.animationFiles.length) {
                        that.finishedLoading.bind(that)
                        that.finishedLoading();
                    }
                }
            );
        }

    }
    finishedLoading(a){
        console.log(this.animations)
        this.tpose.animations = this.animations;
        this.mixer = new THREE.AnimationMixer(this.tpose);
        this.action = this.mixer.clipAction(this.tpose.animations[1]);
        this.action.play();
        this.mixer.addEventListener('loop',this.animationEnd.bind(this));
    }
    animationEnd(){
        console.log('animation end');
        var i= Math.floor(Math.random()*this.tpose.animations.length);
        console.log('playing animation#'+i);
        const endAction = this.mixer.clipAction(this.tpose.animations[i]);
        endAction.enabled = true;
        endAction.setEffectiveTimeScale(1);
        endAction.setEffectiveWeight(1);
        endAction.time = 0;
        endAction.weight=1;

        this.action.crossFadeTo ( endAction, 1, true);
    }

I got all the endAction stuff in animationEnd() from various examples online. In particular, I gather from this that its especially important to set the weight to 1.

How to Embed Images into an Excel File cell (.xlsx) Using JavaScript in a Chrome Extension

I am developing a Chrome extension where I need to create an Excel (.xlsx) file that includes embedded images. I am using JavaScript to fetch image data and SheetJS (xlsx) to generate the Excel file. However, I am unable to insert images directly into the Excel cells; they are only being added as links or not included at all.

Page Html :

<img alt="3W 3.7V 1000mA 300lm Led COB Light Module For Bike Diy Work" src="https://cdn.shopify.com/s/files/1/0744/0764/1366/files/WhatsApp_Image_2024-02-27_at_1.02.54_PM-removebg-preview_result.webp?v=1723519244">

Image URL will be fetched from such HTML Element and embed Image against the URL and place that image in the cell of xlsx

Below is the Code with done the Task but run on Node whcih is protected in extension developing what will be the perfect solution for this

const ExcelJS = require("exceljs");
const axios = require("axios");

async function addImageToExcel() {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("My Sheet");

  // Define some sample data
  const data = [
    {
      id: 1,
      imageUrl:
        "https://cdn.shopify.com/s/files/1/0744/0764/1366/files/1pol100A.webp?v=1717142687",
    },
    {
      id: 2,
      imageUrl:
        "https://cdn.shopify.com/s/files/1/0744/0764/1366/files/schneider-mcb-63-amp-1-pole-500x500_e4d774d1-8d66-4847-8ce2-d3e948dd6a13.webp?v=1717148962",
    },
    {
      id: 3,
      imageUrl:
        "https://cdn.shopify.com/s/files/1/0744/0764/1366/files/100ATOMZNTOM7-1254300MCCB100A4POLECIRCUITBREAKERINPAKISTAN1.webp?v=1716651428",
    },
    {
      id: 4,
      imageUrl:
        "https://cdn.shopify.com/s/files/1/0744/0764/1366/files/s-l300-removebg-preview_result.webp?v=1717755958",
    },
  ];

  // Add column definitions
  worksheet.columns = [
    { header: "ID", key: "id", width: 10 },
    { header: "Image", key: "image", width: 30 }, // Set width to hold images
  ];

  // Load images and add them to the sheet
  for (const item of data) {
    const row = worksheet.addRow({ id: item.id });

    // Set the height of the row
    row.height = 90; // Adjust this value to fit your images

    const imageId = workbook.addImage({
      buffer: (await axios.get(item.imageUrl, { responseType: "arraybuffer" }))
        .data,
      extension: "png",
    });

    worksheet.addImage(imageId, `B${row.number}:B${row.number}`);
  }

  // Save the workbook
  await workbook.xlsx.writeFile("ExcelWithImages.xlsx");
  console.log("Excel file with images saved!");
}

addImageToExcel().catch(console.error); 

Changing _astro dist folder

I’m using Astro JS to build a google chrome extension, I have a problem when using tailwind.

Apparently Astro adds the css files to an _astro folder in the dist but this causes conflicts with google due to:

Filenames starting with “_” are reserved for use by the system.
Could not load manifest.

If I manually change the name of the folder and the link to it in the index.html file it works, but its a pain to be doing this every time

  • Do you know if its possible to change the name of this folder in some astro config?
  • If it isn’t, how could I automate this process for every build?

Cyrillic Domain Not Passed Correctly in Laravel 11 on cPanel Deployment

I have a Laravel 11 web app where I implemented an IDN converter to handle domains written in Cyrillic script, such as монгол.мон, converting them into Punycode (xn--c1aqbeec.xn--l1acc). Locally, it works perfectly. However, after deploying it on cPanel, Cyrillic domains aren’t being processed correctly.

Here’s the controller:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use Algo26IdnaConvertToIdn;

class IDNController extends Controller
{
    public function convert(Request $request)
    {
        $domain = $request->input('domain');
        $idn = new ToIdn();
        $output = $idn->convert($domain);
        return response()->json(['output' => $output]);
    }
}

And this is the Javascript:

document.getElementById('idn-form').addEventListener('submit', function(event) {
    event.preventDefault();
    
    const domain = document.querySelector('#idn-form input[name="domain"]').value;
    const submitButton = document.getElementById('idn-submit');
    submitButton.disabled = true;

    fetch(`/idn?domain=${domain}`)
        .then(response => response.json())
        .then(data => {
            const resultDiv = document.getElementById('idn-result');
            resultDiv.innerHTML = `<p class="text-[#312E81] text-md font-semibold px-4 py-2 rounded-lg">${data.output}</p>`;
            document.getElementById('copy-button').classList.remove('hidden');
            submitButton.disabled = false;
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('idn-result').innerHTML = `<p class="text-red-500">An error occurred. Please try again later.</p>`;
            submitButton.disabled = false;
        });
});

Locally, this setup works fine, returning JSON as expected. However, after deploying on cPanel, I face the following issue: when I input Cyrillic domains, nothing is returned. Upon logging the $domain in the controller, it shows as empty:
[2024-10-03 02:14:03] local.INFO: Domain:

And here’s the log in the error:
[2024-10-03 02:14:03] local.ERROR: Algo26IdnaConvertToIdn::convert(): Argument #1 ($host) must be of type string, null given, called in /home/cctldmn/cctldmn/app/Http/Controllers/IDNController.php on line 16

When I use English letters, it works perfectly. But with Cyrillic domains, the input is not passed correctly. Could it be an encoding issue or some cPanel setting? Any ideas on why Cyrillic domains aren’t being processed?

Images failing to appear in js

I am making a game with JS as the main language, I am experiencing no errors or issues on F12 console, but my images don’t seem to load visually, when I open the F12 menu, under sources they are there next to my JS code and html index file. Code is further below, I’m using express, node.js, tensorflow.js, JS, and html. Console is empty, all in same directory. (local) Apologies for the large pieces of code, the image loading is spread across the whole code.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
  <canvas id="gameCanvas" width="640" height="480"></canvas>
  <script src="script.js"></script>
  </body>
</html>

JS

    const canvas = document.getElementById('gameCanvas');

const ctx = canvas.getContext('2d');

const canvasWidth = 640;
const canvasHeight = 480;
canvas.width = canvasWidth;
canvas.height = canvasHeight;

// Load images
const playerImage = new Image();
playerImage.src = 'player.png';
const projectileImage = new Image();
projectileImage.src = 'projectile.png';
const platformImage = new Image();
platformImage.src = 'platform.png'; 


let platforms = [154, 204];

function checkCollisions() {
  detectPlayerCollisions(player1, player2);

  projectiles.forEach(projectile => {
    if (projectile.isPlayer1) {
      if (isColliding(projectile, player2)) {
        player2.takeDamage(10);  // Example damage; adjust as needed
        projectiles.splice(projectiles.indexOf(projectile), 1);
      }
    } else {
      if (isColliding(projectile, player1)) {Stop
        player1.takeDamage(10);Stop
        projectiles.splice(projectiles.indexOf(projectile), 1);
      }
    }
  });
}

function isColliding(rect1, rect2) {
    return (
        rect1.x < rect2.x + rect2.width &&
        rect1.x + rect1.width > rect2.x &&
        rect1.y < rect2.y + rect2.height &&
        rect1.y + rect1.height > rect2.y
    );
}

// Detect collision between two players
function detectPlayerCollisions(playerA, playerB) {
    if (isColliding(playerA.hitbox, playerB.hitbox)) {
        playerA.takeDamage(5);  // Example damage; adjust as needed
        playerB.takeDamage(5);  // Example damage; adjust as needed
    }
}

class Player {
  constructor(x, y, isPlayer1) {
    this.x = x;
    this.y = y;
    this.width = 32;
    this.height = 32;
    this.speed = 3;
    this.gravity = 0.5;
    this.velocity = { x: 0, y: 0 };
    this.hitbox = {
      x: this.x,
      y: this.y,
      width: this.width,
      height: this.height,
    };
    this.isPlayer1 = isPlayer1;
    this.isJumping = false;
    this.jumpForce = 8;
    this.health = 100;
  }

  takeDamage(amount) {
    this.health -= amount;
  }

  moveLeft() {
    this.velocity.x = -this.speed;
  }

  moveRight() {
    this.velocity.x = this.speed;
  }

  stop() {
    this.velocity.x = 0;
  }

  jump() {
    if (!this.isJumping) {
      this.isJumping = true;
      this.velocity.y = -this.jumpForce;
    }
  }

  shoot() {
    const projectile = new Projectile(this.x + this.width / 2, this.y, this.isPlayer1);
    projectiles.push(projectile);
  }

  update(deltaTime) {
    this.velocity.y += this.gravity * deltaTime;
    this.x += this.velocity.x * deltaTime;
    this.y += this.velocity.y * deltaTime;

    // Update hitbox position
    this.hitbox.x = this.x;
    this.hitbox.y = this.y;
  }

  draw() {
    if (playerImage.complete) {
      ctx.drawImage(playerImage, this.x, this.y, this.width, this.height);
    } else {
      ctx.fillRect(this.x, this.y, this.width, this.height); // Draw rectangle as placeholder
    }
  }
}

class Projectile {
  constructor(x, y, isPlayer1) {
    this.x = x;
    this.y = y;
    this.width = 8;
    this.height = 8;
    this.speed = 5;
    this.isPlayer1 = isPlayer1;
  }

  update() {
    if (this.isPlayer1) {
      this.x += this.speed;
    } else {
      this.x -= this.speed;
    }
  }

  draw() {
    if (projectileImage.complete) {
      ctx.drawImage(projectileImage, this.x, this.y, this.width, this.height);
    } else {
      ctx.fillRect(this.x, this.y, this.width, this.height); // Draw rectangle as placeholder
    }
  }
}

// Create player and platform objects
const player1 = new Player(32, canvas.height - 32, true);
const player2 = new Player(canvas.width - 64, canvas.height - 32, false);
let projectiles = [];

// Input handling
let keysPressed = [];

window.addEventListener('keydown', (event) => {
  keysPressed.push(event.key);
});

window.addEventListener('keyup', (event) => {
  const index = keysPressed.indexOf(event.key);
  if (index !== -1) {
    keysPressed.splice(index, 1);
  }
});

// Function to update game state and send to API
function updateGameState() {
  fetch('http://localhost:3000/update-players', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      players: [
        { id: 1, x: player1.x, y: player1.y, health: player1.health },
        { id: 2, x: player2.x, y: player2.y, health: player2.health }
      ]
    })
  });
}

// Function to sync projectiles with API
function syncProjectiles() {
  fetch('http://localhost:3000/add-projectiles', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      projectiles: projectiles.map(p => ({ x: p.x, y: p.y, isPlayer1: p.isPlayer1 }))
    })
  });
}

function gameLoop(currentTime) {
  const deltaTime = (currentTime - previousTime) / 10000;
  previousTime = currentTime;

  ctx.clearRect(0, 0, canvasWidth, canvasHeight);

  // Player 1 controls
  if (keysPressed.includes('w')) {
    player1.jump();
  }
  if (keysPressed.includes('a')) {
    player1.moveLeft();
  }
  if (keysPressed.includes('d')) {
    player1.moveRight();
  }
  if (keysPressed.includes(' ')) {
    player1.shoot();
  }

  // Update proj and players
  player1.update(deltaTime);
  player1.draw();
  player2.update(deltaTime);
  player2.draw();

  for (let i = 0; i < projectiles.length; i++) {
    projectiles[i].update();
    projectiles[i].draw();
  }

  checkCollisions();

  // Update game for API
  updateGameState();
  syncProjectiles();

  requestAnimationFrame(gameLoop);
}

let previousTime = 0;

requestAnimationFrame(gameLoop);

I tried searching for similar issues, reformatting and even rewriting the code entirely, I’m tired of looking and want a hand, any takers?

Remove extra spaces occupied by a hidden elements in HTML form

I have a form with several elements. There is a check box in the form. If I checked in the check box then the some of form elements got hidden as per requirement but the space occupied by those elements not eliminated. I have tried with below code.

window.addEventListener('load', () => { 
      document.getElementById('cbox1').addEventListener('click', (e) => {
        const show = e.target.checked;
        document.getElementById("end1").style.visibility = show ? 'visible' : 'hidden';
        document.getElementById("tap1").style.visibility = show ? 'visible' : 'hidden';
        document.getElementById("atnd1").style.visibility = show ? 'visible' : 'hidden';
        document.getElementById("lbl1").style.visibility = show ? 'visible' : 'hidden';
        document.getElementById("lbl2").style.visibility = show ? 'visible' : 'hidden';
      });
      });
form[id=fbd1] {
  width : 250px;
  height : 320px;
  position: absolute;
  top: 71%;
  left: 16%;
  background-color: #fff;
  box-shadow: 0 0 20px;
  text-align:center;
  padding-left :10px;
  padding-top :5px;
  border-radius: 8px;
  resize:vertical;
  overflow:auto;
  }
  
  #lbl1,#end1,#tap1,#lbl2,#atnd1 {
    visibility : hidden;
  }
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form id="fbd1" action="submitscript.php" target="dummyframe">
    <textarea id="tbd1" placeholder="Enter your details"></textarea>
    <br>
    <label>Start Time</label>&nbsp;&nbsp;<input id="strt1" type="time">&nbsp;&nbsp;&nbsp;<input id="cbox1" type="checkbox">
    <br><br>
    <label id="lbl1">End Time</label>&nbsp;&nbsp;<input id="end1" type="time">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <br>
    <br>
    <textarea id="tap1" placeholder="Enter plan details"></textarea>
    <br>
    <label id="lbl2">Named By</label>&nbsp;&nbsp;<input id="atnd1" type="text">
    <br><br>
    <input type="submit" id="btn10" value="submit">
  </form>

pro-gallery unable to read option parameters

I am using an npm package ‘pro-gallery’ in React and trying to get some overlay fade and image hover effects as I did in the playground they provided: My Playground

In the playground I can see those effects but when I do it on my application it doesn’t take affect and I am not sure why. Here is my codesandbox. In the playground generated code, it provided incorrect options object which I corrected on my end but I can’t seem to get the same effect?

React: Why is my component re-rendering even though custom hook values aren’t changing?

I’m working with nested custom hooks in React, and I’m experiencing an unexpected re-render in my parent component, even though the value returned from one of the custom hooks remains unchanged. Specifically, the useIsAdmin hook depends on the session data from useSession, but even when the session’s roles don’t change, the parent component re-renders.

Here’s a simplified version of my code:

// Custom hook to check if user is admin
export const useIsAdmin = () => {
  const { data: session } = useSession(); // Fetch session data

  // Check if the user's roles match the required admin roles
  return useMemo(
    () =>
      ADMIN_READ.every((role) =>
        session?.roles?.find((userRole) => userRole === role)
      ),
    [session?.roles]
  );
};

Issue:

The useIsAdmin hook is the middle custom hook. Each time useSession fetches the session, even though the session.roles value remains the same, the parent component still re-renders. I expected the useMemo to prevent re-renders as long as session.roles hasn’t changed.

What I’ve tried:

  • I’ve checked if the roles are deeply equal but the re-render happens regardless.
  • Tried using React.memo for the parent component to prevent unnecessary re-renders, but it still occurs.
  • Verified that session.roles remains identical between renders.

Question:

Why is the parent component re-rendering even though useIsAdmin’s result doesn’t change when session.roles is the same? Is there a problem with how I’m using useSession or useMemo in this nested hook setup?

Additional Info:

  • I’m using React v18.3.1
  • The parent component re-renders whenever useSession fetches data, despite session.roles being unchanged.

Want to prevent the component rerendering whenever last child custom hook return same data

dragend event not fired when dragging into an iTerm2 window

In the snippet below, if the green box is dragged into an app such as Word or Notes, the ‘dragend’ event will fire when the drop occurs.

However, in Chrome v129 on macOS, when I drag the green box into an iTerm2 window, the text “plain text” appears in iTerm2, but no dragend event is fired.

This means that I can’t perform the necessary cleanup I need to do inside the dragend event.

Does anyone know why this might happen only when dragging to some apps, and if there is anything I can do about it?

When testing with Firefox, it works perfectly and I see the dragend event fire.

When testing with Safari 18, the dragend event fires immediately after the dragstart event, and I can’t drag the green box at all.

x.ondragstart = e => {
    console.log('drag started');
  e.dataTransfer.setData('text/plain', 'plain text');
  e.dataTransfer.setData('text/html', 'html text');
}

x.ondragend = e => console.log('drag ended');
#x {
  background-color: green;
  height: 60px;
  width: 60px;
}
<div id="x" draggable="true"></div>

Axios Nested Async/Await, Promise Pending

I’m trying to get data from json file but even after trying multiple variarions i’m still getting promise pending error.

Code snippet as follows:

import axios from "axios";

async function getAuthorsData(){
    const {authorData} = await axios.get('https://gist.githubusercontent.com/graffixnyc/a086a55e04f25e538b5d52a095fe4467/raw/e9f835e9a5439a647a24fa272fcb8f5a2b94dece/authors.json')
    return authorData;
} 

export const getAuthorById = async (id) => {
    let trimId = id.trim();
    if(typeof trimId !== 'string' || trimId == '')
        throw new Error ("Please enter valid author ID.");

    let authorsData = await getAuthorsData();

    authorsData.forEach(author =>{
        if(author.id===trimId)
            return author;
        else
            throw new Error('author not found');
    })
};

I tried various variations, still no progress. I want some output on my terminal after calling the function.

Kafkajs with GCP Apache Kafka not establishing connection succesfully

I’m creating a kafka client consumer (kafkajs 2.2.4) for a microservice hosted in a kubernetes cluster in GCP. I’ve created a producer in another microservice with the same configuration without problems. My issue is that after the ssl/sasl authentication handshake my consumer attempts to authenticate again and I assume that’s the reason it disconnects itself. After disconnecting the service attempts to connect again several times until it crashes. Logging doesn’t provide a lot of information on how to debug this but it happens right after the second sasl handshake according to the logs. Any information on how to approach this would be awesome. I’m using NestJS for the backend.

Here is my configuration:

const brokers = [`${process.env.KAFKA_B1}:${process.env.KAFKA_PORT}`];
    console.log(brokers)

    let kafkaConfig: any = {
      clientId: 'consumer-client',
      brokers: brokers,
      connectionTimeout: 300000,
      enforceRequestTimeout: false,
      logLevel: logLevel.ERROR,
      // retry: {
      //   initialRetryTime: 1000,
      //   retries: 5,
      // },
    };

    if (process.env.KAFKA_SASL_ENABLED) {
      kafkaConfig = {
        ...kafkaConfig,
        ssl: true,
        sasl: {
          mechanism: 'plain', // scram-sha-256 or scram-sha-512
          username: process.env.KAFKA_USERNAME,
          password: process.env.KAFKA_PASSWORD,
        },
      };
    }

    console.log('START creating kafka instance');
    const kafka = new Kafka({
      ...kafkaConfig,
      clientId: `microservice-${process.env.HOSTNAME}`,
    });
    console.log('FINISHED creating kafka instance');
    console.log('START creating kafka consumer');
    const consumer = kafka.consumer({
      groupId: 'microservice',
      sessionTimeout: 90000,
      heartbeatInterval: 30000,
      retry: {
        retries: 5,
        initialRetryTime: 1000,
        maxRetryTime: 60000,
      },
    });

  const topic: ConsumerSubscribeTopics = {
      topics: ['MyTopicStream'],
      fromBeginning: false,
    };

    try {
      console.log('START kafka consumer connection');
      await this.kafkaConsumer.connect();
      await this.kafkaConsumer.subscribe(topic);
      console.log('FINISHED kafka consumer connection');

      console.log('START kafka consumer run');
      await this.kafkaConsumer.run({
        eachMessage: async (messagePayload: EachMessagePayload) => {
          const { topic, partition, message } = messagePayload;
          const prefix = `${topic}[${partition} | ${message.offset}] / ${message.timestamp}`;
          console.log(`- ${prefix} ${message.key}#${message.value}`);
        },
      });
      console.log('FINISHED kafka consumer run');
    } catch (error) {
      console.log('Error: ', error);
    }

Logs I get on disconnect:

network request
InstrumentationEvent {
  id: 22,
  type: 'consumer.network.request',
  timestamp: 1727916074589,
  payload: {
    broker: 'broker-1.kafka-sandbox.us-central1.managedkafka.carbon-sandbox-434719.cloud.goog:9092',
    clientId: 'black-box-black-box-88668575b-pvsp5',
    correlationId: 12,
    size: 52,
    createdAt: 1727916074586,
    sentAt: 1727916074586,
    pendingDuration: 0,
    duration: 3,
    apiName: 'ListOffsets',
    apiKey: 2,
    apiVersion: 3
  }
}
[NestWinston] Error     10/2/2024, 8:41:14 PM [ClientKafka] [ClientKafka] ERROR [BrokerPool] Closed connection {"timestamp":"2024-10-03T00:41:14.593Z","logger":"kafkajs","retryCount":0,"retryTime":50} - {"stack":[null]}  
network request
InstrumentationEvent {
  id: 23,
  type: 'consumer.network.request',
  timestamp: 1727916074609,
  payload: {
    broker: 'broker-0.kafka-sandbox.us-central1.managedkafka.carbon-sandbox-434719.cloud.goog:9092',
    clientId: 'black-box-black-box-88668575b-pvsp5',
    correlationId: 0,
    size: 30,
    createdAt: 1727916074602,
    sentAt: 1727916074602,
    pendingDuration: 0,
    duration: 7,
    apiName: 'SaslHandshake',
    apiKey: 17,
    apiVersion: 1
  }
}
network request
InstrumentationEvent {
  id: 24,
  type: 'consumer.network.request',
  timestamp: 1727916074610,
  payload: {
    broker: 'broker-2.kafka-sandbox.us-central1.managedkafka.carbon-sandbox-434719.cloud.goog:9092',
    clientId: 'black-box-black-box-88668575b-pvsp5',
    correlationId: 0,
    size: 30,
    createdAt: 1727916074608,
    sentAt: 1727916074608,
    pendingDuration: 0,
    duration: 2,
    apiName: 'SaslHandshake',
    apiKey: 17,
    apiVersion: 1
  }
}
[NestWinston] Error     10/2/2024, 8:41:14 PM [ClientKafka] [ClientKafka] ERROR [BrokerPool] Closed connection {"timestamp":"2024-10-03T00:41:14.650Z","logger":"kafkajs","retryCount":1,"retryTime":75} - {"stack":[null]}