Missing source maps for large first-party JavaScript

PageSpeed Insights is giving me the following warning regarding my first-party javascript file:

Missing source maps for large first-party JavaScript

But that makes no sense to me because the first-party javascript file is not minified. It currently has 13,895 lines.

Is there a way to fix the warning without minifying the first-party javascript file?

I tried putting the reference of the source map of a minified third-party javascript plugin (shown below) at the bottom of the first-party javascript. That fixed the warning, but the console showed a ReferenceError about a variable. Therefore, I have to find an alternative solution.

//# sourceMappingURL=someplugin.min.js.map

Bad Request error in passport-google-oauth

I am trying to implement a Google-based authentication using passport.js.
but I am getting Bad Request error

This is the error
enter image description here

This is my main.js file

import express from "express"
import dotenv from "dotenv"
dotenv.config()
import { authRouter } from "./routes/auth"

const app = express()
const port = process.env.PORT

app.use('/auth', authRouter)

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

This is my authRoute

import { Router, Request, Response } from 'express'
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

import passport from "passport"
const router = Router()

if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
    throw new Error('Missing Google OAuth credentials in environment variables');
}

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/google/callback",
},
    (accessToken: any, refreshToken: any, profile: any, done: any) => {
        console.log(`accessToken -> ${accessToken}, refreshToken -> ${refreshToken}, profile -> ${profile} `)
        return done(null, profile)
    })
)

router.use('/google',
    passport.authenticate('google', { session: false, scope: ['profile', 'email'] })
)

router.get('/google/callback',
    passport.authenticate('google', { failureRedirect: '/' }),
    (req: Request, res: Response) => {
        console.log("inside callback")
        res.redirect('/')
    }
)

export { router as authRouter }

Could anyone help me in identifying the problem?

Mask String content and copy content using button

I have this table row:

 {apiKeyData.api_token && (
                <div className="flex items-center gap-24 leading-6">
                  <FuseSvgIcon>heroicons-outline:key</FuseSvgIcon>
                  {apiKeyData.api_token}
                </div>
            )}

How I can limit the displayed String by only showing first 3 and last 3 characters and also add a button to copy the entire content?

How to move cursor from parent node to child node

I have a div contenteditable parent node and onclick a paragraph child node is added as the first element child of the div. I am faced with difficulties to transfer the cursor from the div contenteditable parent node to the newly created paragraph child node so that when a use writes a text it is written onto the paragraph node.

This is the parent node

   <div :ref="(el: HTMLDivElement) => { editorContainerRef = el; }" contenteditable>
   </div>

And (editorContainerRef.value as HTMLDivElement) is the reference to parent node (VueJS)

Here I am adding the child node onClick event

const newParagraph = document.createElement('p');
newParagraph.className='d-block paragraph';
newParagraph.setAttribute('contenteditable', 'true');
newParagraph.innerText = '';
(editorContainerRef.value as HTMLDivElement).appendChild(newParagraph);

I have tried clicking the paragraph node programatically and also focused on the element with hope that the cursor will be transferred to the the paragraph node but it doesn’t work as expected

((editorContainerRef.value as HTMLDivElement)?.firstElementChild as HTMLParagraphElement).focus();
((editorContainerRef.value as HTMLDivElement)?.firstElementChild as HTMLParagraphElement).click();

Please I need help on how to solve this problem.

Why is the `.getAnimations()` rejecting all promises when a HTML dialog element is closed?

I want to trigger a function after a dialog element is closed. I use transitions to fade out the dialog and it’s backdrop, so I want to wait till all transitions are done.

I searched how to do this and implemented that feature (MDN Web Docs).

But sometimes the promises are rejected and sometimes the’ll finish. I tried a lot of things with the transition-timing-functions and also without the new allow-discrete behavior, but it will still fail sometimes.

Anybody knows if this is correct behavior? Or can it be a bug in the browser?
I’m working on Chrome, because Safari and Firefox aren’t supporting the overlay transition.

const $button = document.querySelector('button');
const $dialog = document.querySelector('dialog');

$dialog.addEventListener('close', async function() {
  const animations = $dialog.getAnimations();

  if (animations.length) {
    await Promise.any(animations.map(animation => animation.finished));
    console.log('After close');
  }
});

$button.addEventListener('click', function() {
  if ($dialog.open) {
    $dialog.close();
  } else {
    $dialog.showModal();
  }
});
.dialog {
  --_transition-duration: 200ms;
  border: 0;
  border-radius: .25rem;
  box-shadow: 0 0.0625rem .5rem 0 rgb(0, 0, 0, .1);
  opacity: 0;
  overscroll-behavior: contain;
  padding: 0;
  transition-behavior: allow-discrete;
  transition-duration: var(--_transition-duration);
  transition-property: display, opacity, overlay, scale;
  transition-timing-function: linear;
  width: min(calc(100% - 2rem), 30rem);

  &[open] {
    opacity: 1;
    scale: 1;

    &::backdrop {
      opacity: 1;
    }
  }

  &::backdrop {
    background-color: rgb(0, 0, 0, .375);
    opacity: 0;
    transition-behavior: allow-discrete;
    transition-duration: var(--_transition-duration);
    transition-property: display, opacity, overlay;
    transition-timing-function: linear;
  }

  @starting-style {
    &[open] {
      opacity: 0;
      scale: .9;
    }

    &[open]::backdrop {
      opacity: 0;
    }
  }
}
<button>Open Modal</button>
<dialog class="dialog">
  <div>
    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Magnam ipsum aut animi exercitationem, obcaecati recusandae rem mollitia qui voluptatum. Aliquid amet rerum magni, enim perferendis dignissimos officiis maxime unde tempore!</p>
  </div>
</dialog>

How to read json into variable?

How can I read a json into a variable to be used throughout http file, i.e as in:

# myrequest.http content
< {%
    import readFile from './readFile.js';
    client.global.set("DATA", readFile('data.json'));
%}
POST http://localhost/api/v1/model
Content-Type: application/json

{{DATA}}

POST http://localhost/api/v2/model
Content-Type: application/json

{{DATA}}

Testing exception thrown by mock in jest

I’m trying to test for an async function to properly handle an exception getting thrown by a dependency call to another async function within its body.

I’m replacing the dependency function with a Jest mock that returns a rejected promise and following guidelines on how to set expectations according to official docs. But I find it’s not working as expected. So I built a demo test to check that the exception gets actually thrown but the await expect ... statement doesn’t match.

import { jest } from '@jest/globals';

const inner = jest.fn();
const underTest = async () => await inner();

test('async mock throws within async function', async () => {
  inner.mockRejectedValue('Error');

  try {
    await underTest();
    expect('Should not reach this statement').toBeUndefined();
  } catch (err) {
    expect(err).toEqual('Error');
  }
  await expect(underTest()).rejects.toThrow();
});

Notice in the output how the first call the expect statement within the catch block gets reached and passes, but the await expect ... statement below fails as if underTest didn’t throw.

$ npm t -- lib/asyncThrow.test.js

> node --experimental-vm-modules node_modules/jest/bin/jest.js lib/asyncThrow.test.js

(node:43103) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  lib/asyncThrow.test.js
  ✓ mock gets called from async function (2 ms)
  ✕ async mock throws within async function (1 ms)

  ● async mock throws within async function

    expect(received).rejects.toThrow()

    Received function did not throw

      19 |     expect(err).toEqual('Error');
      20 |   }
    > 21 |   await expect(underTest()).rejects.toThrow();
         |                                     ^
      22 | });
      23 |

      at Object.toThrow (node_modules/expect/build/index.js:218:22)
      at Object.<anonymous> (lib/asyncThrow.test.js:21:37)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        0.098 s, estimated 1 s

What am I missing?

Issue with Service Worker Scope and React Navigation

I’m having trouble with my service worker’s scope when using React’s navigate() function. I am having two service worker one with default scope another one with the scope /app1/, app1 is not being applied correctly when navigating within the React app.

When I navigate to http://localhost:4000/app1/users using React’s navigate() function, the service worker with the scope /app1/ is not being triggered. However, direct navigation in the browser works as expected.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./service-worker.js')
    .then(function(registration) {
      console.log('Service Worker registered with scope:', registration.scope);
    })
    .catch(function(error) {
      console.log('Service Worker registration failed:', error);
    });

    // Register the second service worker with a different scope
  navigator.serviceWorker.register('./service-worker1.js', { scope: '/app1/' })
  .then(function(registration) {
    registration.update();
    console.log('Another Service Worker registered with scope:', registration.scope);
  })
  .catch(function(error) {
    console.log('Another Service Worker registration failed:', error);
  });

React Navigation:

navigate('/app1/users');

Expected Behavior
The service worker with the scope /app1/ should handle requests to http://localhost:4000/grit/users when navigating using React’s navigate() function.

Actual Behavior
The service worker with the scope /app1/ is not being triggered when using React’s navigate() function, but works with direct browser navigation.

i want create online editor but not working [closed]

   // C# snippets
                    { caption: "Console.WriteLine", value: "Console.WriteLine(${1:"message"});", meta: "C#" },
                    { caption: "if", value: "if (${1:condition}) {nt${2:// body}n}", meta: "C#" },
                    { caption: "for", value: "for (int ${1:i} = 0; ${1:i} < ${2:n}; ${1:i}++) {nt${3:// body}n}", meta: "C#" },

this code given me a chatgpt but it’s doesn’t work correctly, i want when user typing any command of c# language then automatically that text take a appropriate color like a visual studio or vs code

Referenced collection field returned null in result

I have this mongoose aggregate that returns the right records but do not include fields in the lookup collection i.e referenced collection.

These are my schemas:

const usersSchema = mongoose.Schema(
  {    
        fullname: {
        type: String,
        required: [true, 'First Name cannot be empty'],
        trim: true,
        index: true,
      },             
    email: {
      type: String,
      validate: [validator.isEmail, 'Provide a valid email'],
      trim: true,
    },
   password: {
      type: String,
      required: [true, 'Password is required'],
      },
}, {
  timestamps: true,
},
 
);
   
const Users = mongoose.model('User', usersSchema);
module.exports = Users;
const sub_origin_info_schema = mongoose.Schema({

  sub_garrage_user1: { //It is an object ID of users collection
    type: String,      
    required: false,     
  },
  garrage_name1: {
    type: String,      
    required: false,     
  },
sub_garrage_user2: { //It is an object ID of users collection
    type: String,      
    required: false,     
  },
  garrage_name2: {  
    type: String,      
    required: false,     
  },

  })

const motorSchema = new mongoose.Schema(
 {
    user_id:{ 
        type: { type: Schema.Types.ObjectId, ref: 'User'},
    },
garrage_of_origin_user:{ //It is an object ID of users collection
        type: String,
        required: true,
    },

    motor_code: {
        type: String,            
        required: true,
        unique: true,
    },       
    motor_name: {
        type: String,            
        required: true,
    },
    motor_number: {
        type: String,            
        required: true,
    },
    imo_number: {
        type: String,            
        required: true,
    },
    garrage_of_origin: {
        type: String,            
        required: true,
    },
journey_date: {
        type: String,            
        required: true,
    },

sub_origin_garage: sub_origin_info_schema,

    }, 
 {
    timestamps: true,
  },
);

const Motors = mongoose.model('Motor', motorsSchema);
module.exports = Motors;

The query worked but does not work as perfectly. It doesn’t include the fullname and email of the referenced Collection using the field mentioned.

I want to achieve two things,

  1. I want to pull the user details (fullname and email) from the Users collection using the garrage_of_origin_user field in the Motors schema collection. The query worked but the fullname and email are null i.e they were not pulled.

  2. How do I pull details (fullname and email) of the users in the subdocument sub_origin_garrage array object which are “sub_garrage_user1” and “sub_garrage_user2” fields? Note that there are users in the subdocuments (sub_origin_garage) too. How do I use lookup to pull out the fields in the users collection for this 3 users i.e garrage_origin_user, sub_garrage_user1 and sub_garrage_user2 in one document?

Motor.aggregate([
      //{ $match : { '_id' : '674ed7fd61f952ddf3e4a661' } },
      { $unwind: "$sub_origin_garage" },
      { $unwind: "$sub_origin_garage.sub_garrage_user1" },
        { $match : 
          { $or: [ 
            { 'sub_origin_garage.sub_garrage_user1' : '6750838a51d231d3178343c7' },
            { 'sub_origin_garage.sub_garrage_user2' : '6750838a51d231d319656209' },   
       ]
        } 
      },
        { $sort : {journey_date: -1} },
                {
          "$lookup": {
              "from": "users",
              "localField": "garrage_of_origin_user",
              "foreignField": "_id",
              "as": "motorDriver"
          }
      },
      {   $project: {       
        motor_code: 1,
        motor_name: 1,
        motor_number: 1,
        imo_number: 1,
        garrage_of_origin: 1,
        journey_date: 1,
       'sub_origin_garage.garrage_name1': 1,
       'sub_origin_garage.garrage_name2': 1,
        motorDriver: { fullname: 1, email: 1 }
        }
    }
  
    ])
    .then(response => {

      res.status(200).json({
        status: 'success', 
           response      
      });     
    })
    .catch(error => {
        res.json({
            message: `An error occured!: ${error}`
        })
    })

How to create custom URL in a one-pager?

I am developing a website using Kirby CMS, and the commission demands that the site remains a one-pager.

I am using the following structure where each article can be created in the panel, and customized (text, style, images …etc)

<?php foreach ($page->articles()->toStructure() as $article): ?>
    <div class="main" id="article-<?= $article->slug() ?>">
        <div class="container" onclick="toggleSibling(this);">
            <div class="Title"><?= $article->title() ?></div>
            <div class="Genre"><?= $article->genre() ?></div>
            <div class="Publisher"><?= $article->publisher() ?></div>
            <div class="Datum"><?= $article->datum()->toDate('m/Y') ?></div>
        </div>

        <!-- Apply the selected style dynamically -->
        <div class="content <?= $article->style() ?>">
            <div class="Info">
                <!-- <p>Information</p> -->
                <?= $article->info()->kt() ?>
            </div>
            <div class="Image">
            <!-- <p>Gallery</p> -->
                <div class="swiper">
                    <div class="swiper-wrapper">
                        <?php foreach ($article->images()->toFiles() as $image): ?>
                            <div class="swiper-slide">
                                <img src="<?= $image->url() ?>" alt="<?= $image->alt() ?>">
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="swiper-scrollbar"></div>
                    <button class="slick-prev"></button>
                    <button class="slick-next"></button>
                </div>
            </div>
            <div class="Page">
            <!-- <p>Index</p> -->
            </div>
            <div class="Text">
            <!-- <p>Content</p> -->
                <?= $article->text()->kt() ?>
            </div>
        </div>
    </div>
<?php endforeach; ?>

The way it works is that each time an article is clicked, the main content becomes visible, which is executed with the following code:

function toggleSibling(element) {
  const content = element.nextElementSibling;

  // Close all other active content elements
  const allContent = document.querySelectorAll('.content.active');
  allContent.forEach(openContent => {
    if (openContent !== content) {
      openContent.classList.remove('active');
      Array.from(openContent.children).forEach(child => {
        child.style.transform = "";
        child.style.opacity = "";
        child.style.transition = "";
      });
    }
  });

  // Toggle the active class on sibling content
  content.classList.toggle('active');

  if (content.classList.contains('active')) {
    // Add the falling animation
    content.classList.add('fall');
    setTimeout(() => {
      content.classList.remove('fall');
      console.log("Falling animation removed from:", content); // Debugging animation reset
    }, 500);
  } else {
    // Reset styles if content is closed
    content.classList.remove('active');
    Array.from(content.children).forEach(child => {
      child.style.transform = "";
      child.style.opacity = "";
      child.style.transition = "";
    });
  }
}

What I am trying to implement is a way to utilize custom URL’s for each article. When a user accesses said URL, it takes them to the article and toggles the content.

The page should remain a one-pager.

Thank you for the help in advance!

How to Decrypt Post Data from hCaptcha? [closed]

I’m currently working with hCaptcha and I need to decrypt or extract the post data that is being sent when the user solves the captcha. I’ve tried several approaches, but I can’t seem to find a way to properly decrypt the information that is sent in the POST request after the hCaptcha challenge is completed.

Has anyone had experience with this or could point me in the right direction? Any insights or methods for decrypting or accessing the post data would be greatly appreciated!

Thanks in advance!

web: https://authenticate.riotgames.com/

How to Decrypt Post Data from hCaptcha?

Why does instantiating a class that relies on an API pull work outside routes but fail inside a POST route in Node.js?

I am using cPanel to deploy my Node.js application and working with CommonJS modules. My app uses a class, PastWeather, which fetches data from an external API.

When I instantiate the class outside any route, it works as expected, and I see the correct response in my terminal. For example:

try {
    const PastWeather = require('./pastWeather.js');
    const testInstance = new PastWeather('GHCND:USC00051547');
    console.log("Test instance created successfully:", testInstance);

    // Call a method from the class
    testInstance.parseData()
        .then(reply => {
            console.log("Parse Data executed successfully:", reply);
        })
        .catch(error => {
            console.error("Error during parseData execution:", error);
        });
} catch (error) {
    console.error("Error initializing PastWeather instance:", error);
}

However, when I move this logic inside a POST route like this:

app.post('/getLatandLang', async (req, res) => {
    try {
        const PastWeather = require('./pastWeather.js');
        const testInstance = new PastWeather('GHCND:USC00261327');
        console.log("Instance created successfully:", testInstance);

        res.json({
            message: "Instance created successfully",
            testInstance: testInstance.locationID,
        });
    } catch (error) {
        console.error("Error in /getLatandLang route:", error);
        res.status(500).json({
            message: "Error occurred while creating instance",
            error: error.message,
        });
    }
});

When I send a POST request to /getLatandLang, the request hangs and no response is sent. Additionally, the PastWeather instance seems to fail silently. I don’t see any errors in my logs.

I have tried taking the instantiation of the class that relies on the API pull outside of the POST request. When instantiated globally (outside any route), the class works as expected, and all subsequent data is retrieved correctly. However, when instantiated within the POST request, the request hangs, and the class fails to initialize or function properly, and my actual website usually times out without any error showing up.

Previous hash and data_hash not matching in hyper ledger fabric

I am working on the fabric test network trying to fetch blocks by number and check the block hash, and i use fabric 2.5 with the new fabric gateway api. I insert a data and check the transaction for the consicutive transaction to check weather i get the data hash on the next block previous hash. but they both are always different when i check with the api.

   {
    "Block Number": "10",
    "Previous Hash": "KSDy3jiB5Y15AT3W4PRqQWUTOarT50oKE8S100na0Ys=",
    "Data Hash": "VBZBIkTTggb23aBuC2xs7+bfCk1EYeKhMPfvQNCL0ZI="
}

{
    "Block Number": "11",
    "Previous Hash": "Zf8YhOJlgTcrWbqm+8up4kGcrNffHMgDFnF++gnI3Dk=",
    "Data Hash": "hY1pO7ljvlsNklmZBKksmTFreLRKNRX18dbvFk+5Y1g="
}

The above are the result returned after each transaction.

I have also directly queried from the cli using the command:

peer channel getinfo -c mychannel

where i got different value for data hash but my previous hash was similar in both the case

2024-12-27 11:43:47.409 IST 0001 INFO [channelCmd] InitCmdFactory -> Endorser and orderer connections initialized
Blockchain info: {"height":11,"currentBlockHash":"Zf8YhOJlgTcrWbqm+8up4kGcrNffHMgDFnF++gnI3Dk=","previousBlockHash":"KSDy3jiB5Y15AT3W4PRqQWUTOarT50oKE8S100na0Ys="}

2024-12-27 11:49:19.022 IST 0001 INFO [channelCmd] InitCmdFactory -> Endorser and orderer connections initialized
Blockchain info: {"height":12,"currentBlockHash":"1lbnSQSEWoJok327h6me1b7a5vgSdY8TGXA/uRUQDYo=","previousBlockHash":"Zf8YhOJlgTcrWbqm+8up4kGcrNffHMgDFnF++gnI3Dk="}

SDK and protos version:

"@hyperledger/fabric-gateway": "^1.7.1"
"@hyperledger/fabric-protos": "^0.2.2"

Iam using the fabric sample network and modifying the asset transfer basic gateway code.

app.get("/getBlockByNumber/:blockNumber", async (req, res) => {
  try {
    let { blockNumber } = req.params;
    blockNumber = blockNumber.replace(/"/g, "");
    blockNumber = blockNumber.replace(/s+/g, " ").trim();

    const network = gateway.getNetwork("mychannel");
    const blockBytes = await network
      .getContract("qscc")
      .evaluateTransaction("GetBlockByNumber", network.getName(), blockNumber);

    console.log(
      `Got block for block number ${blockNumber} with length ${String(
        blockBytes.length
      )}`
    );
    const protos = require("fabric-protos");

    // Deserialize the block
    const block = protos.common.Block.decode(blockBytes);

    // Access block details
    const data = {
      "Block Number": block.header.number.toString(),
      "Previous Hash": Buffer.from(block.header.previous_hash).toString(
        "base64"
      ),
      "Data Hash": Buffer.from(block.header.data_hash).toString("base64"),
    };


    res.send(data);
  } catch (error) {
    console.error("Error in getBlockByNumber:", error);
    res.status(500).send("Failed to fetch block by block number");
  }
});