Download public “Shared with Anyone” files from google drive folder via Node.js and googleapis

I am trying to read a list of files in a publicly shared Google Drive file. I am trying to identify a particular csv file by name and download it daily as the folder maintainer creates a new version each day. However, all the answers I have found don’t seem to work.

The code below returns an empty array as it seems like it is looking for a folderid in the service work drive. I have shared the public folder with the service worker but it still does not find it.

const googleDrive = async() => {
    const drive = google.drive({version: 'v3', auth})
    return drive
}

export const readPublicGoogleFolder = async(folderId: string) => {
    try{
        const gd = await googleDrive();
        // const shareLink = `https://drive.google.com/drive/folders/${folderId}`
        const shareLink = `${folderId}`
        console.log({shareLink})
        const publicFiles = await gd.files.list({q:`'${shareLink}' in parents`})
        console.log({publicFiles })  
        return publicFiles ;
        
    } 
    catch(err: any){
        console.log({err});
        return null;
    }
   
}

Using either the ‘sharelink’ url or ‘sharelink’ id the data returns an empty array.

Is there a way to achieve this?

Thnks in advance.

I have shared the folder with the service account, but it doesn’t appear to be present when I query all the files.

Webpack cannot resolve modules

I have an old React app which I’m trying to run locally, but I encountered some issues regarding querystring and pollyfils. I tried to circumvent it with webpack, but seems I made even more issues. Here are my files:

packages.json:

{
  "name": "test-immersion",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "immersion-presentation": "^1.0.0",
    "os-browserify": "^0.3.0",
    "path-browserify": "^1.0.1",
    "querystring-es3": "^0.2.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-scripts": "5.0.1",
    "webpack": "^5.98.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.10.4",
    "@babel/core": "^7.10.4",
    "@babel/preset-env": "^7.10.4",
    "@babel/preset-react": "^7.10.4",
    "babel-loader": "^8.1.0",
    "webpack-cli": "^6.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "webpack",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "pdf": "node ./node_modules/immersion-presentation/make-pdf"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

.babelrc:

{
    "presets" : ["@babel/preset-env", "@babel/preset-react"]
}

webpack.config.js:

const path = require( 'path' );
const webpack = require( 'webpack' );

module.exports = ( env, options ) => {
    return {
        entry: path.resolve(__dirname, 'src', 'index.js'),
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        },
        mode: 'development',
        resolve: {
            fallback: { 
                "querystring": require.resolve("querystring-es3"),
                "path": require.resolve("path-browserify"),
                "os": require.resolve("os-browserify/browser"),
                "util": false,
            },
        },
        module: {
            rules: [
                {
                    test: /.(js|jsx)$/,
                    exclude: /(node_modules)/,
                    loader: 'babel-loader',
                    options: { presets: ["@babel/env"]}
                },
                {
                    test: /.css$/,
                    use: ["style-loader", "css-loader"]
                }
            ]
        },
        plugins: [new webpack.HotModuleReplacementPlugin()]
    }
};

src/index.js:

import React from "react";
import ReactDOM from "react-dom";
import Presentation from "./Presentation";

// Not using React.StrictMode because of performance issues (renders everything twice)
const rootEl = document.getElementById("root");
ReactDOM.render(<Presentation />, rootEl);

if (module.hot) {
  module.hot.accept("./Presentation", () => {
    const NextPresentation = require("./Presentation").default;
    ReactDOM.render(<NextPresentation />, rootEl);
  });
}

src/Presentation.js:

import React from "react";

/* eslint-disable jsx-a11y/iframe-has-title, jsx-a11y/alt-text,  */
/* eslint-disable no-unused-vars */

import { useState } from "react";

import {
  AnimateSVG,
  Morph,
  m,
  M,
  Show,
  Notes,
  Portal,
  timeline,
  range,
  themes,
} from "immersion-presentation";

import "immersion-presentation/dist/index.css";
import step from "immersion-presentation/dist/step.macro.js";

const {
  Presentation,
  Slide,
  BibliographySlide,
  TitleSlide,
  TableOfContentsSlide,
  SectionSlide,
  QuestionSlide,
  ConclusionSlide,
  Figure,
  List,
  Item,
  Cite,
  Box,
  Qed,
} = themes.modern;

function App() {
  return (
    <Presentation>
      <Slide steps={[1, 2, 3]}>The step is {step}!</Slide>
    </Presentation>
  );
}

export default App;

I’m using node version 16.20.2 and npm version 8.1.0, and when I run npx webpack --config webpack.config.js it throws multiple errors about

cannot resolve ‘fs’

cannot resolve ‘module’

in some packages. Any ideas how to run it correctly?

Could not Resolve all files for configuration ‘:classpath’. could not find com.facebook.react:react-native-gradle-plugin:0.73.0

been facing this issue for the past 3 weeks. building the app always returns this error:
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'TranslatorApp'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find com.facebook.react:react-native-gradle-plugin:0.73.0.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/facebook/react/react-native-gradle-plugin/0.73.0/react-native-gradle-plugin-0.73.0.pom
       - https://repo.maven.apache.org/maven2/com/facebook/react/react-native-gradle-plugin/0.73.0/react-native-gradle-plugin-0.73.0.pom
       - https://plugins.gradle.org/m2/com/facebook/react/react-native-gradle-plugin/0.73.0/react-native-gradle-plugin-0.73.0.pom
     Required by:
         project :

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

------------------------------------------------------------
Gradle 8.0
------------------------------------------------------------

Build time:   2023-02-13 13:15:21 UTC
Revision:     62ab9b7c7f884426cf79fbedcf07658b2dbe9e97

Kotlin:       1.8.10
Groovy:       3.0.13
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          17.0.12 (Oracle Corporation 17.0.12+8-LTS-286)
OS:           Windows 11 10.0 amd64

java version "17.0.12" 2024-07-16 LTS
Java(TM) SE Runtime Environment (build 17.0.12+8-LTS-286)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.12+8-LTS-286, mixed mode, sharing)


I have tried to change the dependencies to try to find a compatable version. I am starting to think that the path is not being recognised or something. Debugging has not really gone far

frontend/Package.json

{
  "name": "translator-app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "test": "jest",
    "clean": "rm -rf node_modules && npm install && cd android && ./gradlew clean && cd ..",
    "postinstall": "npx pod-install"
  },
  "dependencies": {
    "@react-native-firebase/app": "^17.3.2",
    "@react-native-firebase/ml": "^17.3.2",
    "@react-native-google-signin/google-signin": "^8.0.0",
    "@react-navigation/native": "^6.1.5",
    "@react-navigation/stack": "^6.3.16",
    "react": "^18.0.0",
    "react-native": "^0.73.0",
    "react-native-gesture-handler": "^2.12.0",
    "react-native-reanimated": "^3.4.0",
    "react-native-vision-camera": "^3.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.23.6",
    "@babel/runtime": "^7.23.6",
    "@react-native-community/cli": "latest",
    "@react-native/gradle-plugin": "0.73.0",
    "babel-jest": "^29.5.0",
    "jest": "^29.5.0",
    "metro-react-native-babel-preset": "^0.77.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

android/build.gradle

pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }

}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "TranslatorApp"
include(":app")

android/build.gradle

buildscript {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:8.0.2")
        classpath("com.facebook.react:react-native-gradle-plugin:0.73.0")    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url("$rootDir/../frontend/node_modules/@react-native/gradle-plugin") } 
    }
}

Frontend/app/src/build.gradle

plugins {
    id("com.android.application")
    id("com.facebook.react")
    id("kotlin-android")
}

android {
    namespace = "com.translatorapp"
    compileSdk = 33

    defaultConfig {
        applicationId = "com.translatorapp"
        minSdk = 21
        targetSdk = 33
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                    getDefaultProguardFile("proguard-android-optimize.txt"),
                    "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
}

dependencies {
    classpat


h("com.facebook.react:react-native-gradle-plugin:0.73.0")    implementation("androidx.appcompat:appcompat:1.4.1")
    implementation("androidx.core:core-ktx:1.8.0")
    implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.22")
    implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
}

PS: The system envirnomental variables are all set up and connected the Path variable as well.

tried updating and downgrading the dependencies. went from java 17 –> java 11 in one week 🙂
fixing the environmental variables contantly with changes.
always updating the package.json

I have noticed that when I hover over the path reference in the code. nothing happens unlike other paths which return the whole path in that pop up window when highlighting text.

javascript dropdown onchange window.href

I have a preexisting Java React app where on change of a dropdown it changes the
window.location.href to the same page URL but with a different query string.

window.location.href = `/newQS?string=abc`

It works on local but it’s losing the full origin on the dev branch.

Will this solution work? :

window.location.href = window.location.origin + `/newQS?string=abc`

If not, what’s the best solution?

The Apple Pay button is not showing in the PayPal integration

I tested this code locally using the same .env with Ngrok and my server (rehosting localhost:3000 like Ngrok), and the button appears on both Mac and iPhone. However, when I deploy it on Netlify with a domain and HTTPS, the button doesn’t appear. I’ve added the Apple well-known file to the backend, and I’ve also registered the domain with PayPal for Apple Pay.

import { useEffect, useState } from "react";
import { PayPalScriptProvider, PayPalButtons, FUNDING } from "@paypal/react-paypal-js";
import axios from "axios";

const PayPalPayment = ({ fundingSource, amount, payee, fee, onOrder }) => {
    const [test, setTest] = useState('')
    return (
        <PayPalButtons
            fundingSource={fundingSource}
            style={{ layout: "vertical" }}
            createOrder={async () => {
                try {
                    const response = await axios.post("/jobs/payment/create", {
                        amount,
                        payee,
                        fee,
                    });
                    console.log("response", response.data.orderId.orderId);
                    return response.data.orderId.orderId;
                } catch (error) {
                    console.error("Error creating order:", error);
                    return null;
                }
            }}
            onApprove={async (data) => {
                try {
                    const response = await axios.post("/jobs/payment/capture", {
                        orderID: data.orderID,
                    });
                    onOrder(response.data.paymentID);
                } catch (error) {
                    console.error("Error capturing payment:", error);
                }
            }}
        />
    );
};



const PaypalButton = ({ amount, payee, onOrder }) => {


    const original_amount = (amount / 1.2).toFixed(2)
    const fee = amount - original_amount;

    // Card fee: 2.99% + 0.49 on the platform's 20% cut
    const cardFee = fee - (amount * 0.0299 + 0.49);

    // PayPal fee: 3.49% + 0.49 on the platform's 20% cut
    const paypalFee = fee - (amount * 0.0349 + 0.49);

    const applePayFee = fee - (amount * 0.0409 + 0.49);

    return (

        <div className="paypal-pay-button">
            <PayPalPayment fundingSource={FUNDING.PAYPAL} amount={amount} payee={payee} fee={paypalFee} onOrder={onOrder} />
            <PayPalPayment fundingSource={FUNDING.APPLEPAY} amount={amount} payee={payee} fee={applePayFee} onOrder={onOrder} />
            <PayPalPayment fundingSource={FUNDING.CARD} amount={amount} payee={payee} fee={cardFee} onOrder={onOrder} />
        </div>

    );
}

export default PaypalButton;

Why my js canvas code overwriting fill and stroke style of previous elements?

I have a problem with image that I am trying to draw on HTML canvas. I need element after //Teren fracht to have different fill colour than previous elements. But for some reason when I use fillStyle on it, it override fillStyle of previous elements. I tried to use ctx.closePath() but it didn’t worked. I have no more ideas what else I can do. In addition the same thing is happening with strokeStyle. My code is like this:

Html file:

<!Doctype html>
<html>
    <head>
        <title>MCL Yard</title>
    </head>
    <body>
        <canvas id="mainCanvas"></canvas>
        <script src="jQuery.min.js"></script>
        <script src="parkingplace.js"></script>
        <script src="building.js"></script>
        <script src="gates.js"></script>
        <script src="main.js"></script>
    </body>
</html>

parkingplace.js:

const parkingSlot = {
    width: 12,
    length: 22
};

function drawParkingPlace(ctx, position, name, angle)
{
    ctx.beginPath();
    ctx.rect(position.x, position.y, parkingSlot.width, parkingSlot.length);
    ctx.fillStyle = "lightgrey";
    ctx.fill();
    ctx.strokeStyle = "black";
    ctx.stroke();
    ctx.save();
    ctx.translate(position.x, position.y);
    ctx.rotate(Math.PI/2);
    ctx.textAlign = "center";
    ctx.fillStyle = "black";
    ctx.fillText(name, parkingSlot.length/2, -2);
    ctx.restore();
}

main.js:

$( document ).ready(function() {
    // Get the canvas element form the page
    var canvas = document.getElementById("mainCanvas");

    /* Rresize the canvas to occupy the full page, 
    by getting the widow width and height and setting it to canvas*/

    canvas.width  = 200*parkingSlot.width;
    canvas.height = 140*parkingSlot.width + 2*parkingSlot.length + 200;

    var ctx = canvas.getContext("2d");
    const middlePoint = {
        x: canvas.width/2, 
        y: canvas.height/2
    };
    ctx.font = "8px Arial";
    var buildingPoints = drawBuildingShape(ctx, middlePoint);
    drawGates(ctx, buildingPoints); 
});

gates.js:

function drawGates(ctx, buildingPoints){
    draw500Gates(ctx, buildingPoints.topStart);
    draw400Gates(ctx, buildingPoints.inTopStart);
    draw600Gates(ctx, buildingPoints.middleStart);
    draw100Gates(ctx, buildingPoints.unloadingStart);
    draw900Gates(ctx, buildingPoints.topFreightStart);
    draw300Gates(ctx, buildingPoints.rightFingerStart);
    draw800Gates(ctx, buildingPoints.bottomFreightStart);
    draw200Gates(ctx, buildingPoints.rightFingerBottomStart);
}

function draw500Gates(ctx, startPosition)
{
    var j = 0;
    for(let i = 500; i <= 564; i++)
    {
        if(i != 526 && i != 547)
        {
            drawParkingPlace(ctx, { x: startPosition.x + j*parkingSlot.width, y: startPosition.y - parkingSlot.length }, i);
        }
        j++;
    }
}

function draw400Gates(ctx, startPosition)
{
    var j = 0;
    for(let i = 449; i > 400; i--)
    {
        if(i != 423)
        {
            drawParkingPlace(ctx, { x: startPosition.x + j*parkingSlot.width, y: startPosition.y }, i);
        }
        j--;
    }
}

function draw600Gates(ctx, startPosition)
{
    var j = 0;
    ctx.save();
    ctx.translate(startPosition.x, startPosition.y);
    ctx.rotate(-Math.PI/2);
    for(let i = 601; i <= 606; i++)
    {
        drawParkingPlace(ctx, { x: parkingSlot.width + parkingSlot.length + j*parkingSlot.width, y: 0 }, i);
        j++;
    }
    ctx.restore();
}

function draw100Gates(ctx, startPosition)
{
    var j = 0;
    ctx.save();
    ctx.translate(startPosition.x, startPosition.y);
    ctx.rotate(-Math.PI/2);
    for(let i = 101; i <= 141; i++)
    {
        if(i!=119)
        {
            drawParkingPlace(ctx, { x: -j*parkingSlot.width, y: 0}, i);
        }
        j++;
    }
    ctx.restore();
}

function draw900Gates(ctx, startPosition)
{
    var j = 0;
    for(let i = 926; i > 900; i--)
    {
        if(i != 913 && i!= 914)
        {
            drawParkingPlace(ctx, { x: startPosition.x + j*parkingSlot.width, y: startPosition.y }, i);
        }
        j--;
    }
}

function draw300Gates(ctx, startPosition)
{
    var j = 0;
    for(let i = 339; i > 300; i--)
    {
        if(i != 313)
        {
            drawParkingPlace(ctx, { x: startPosition.x + j*parkingSlot.width, y: startPosition.y }, i);
        }
        j--;
    }
}

function draw800Gates(ctx, startPosition)
{
    var j = 0;
    for(let i = 826; i > 800; i--)
    {
        if(i != 813)
        {
            drawParkingPlace(ctx, { x: startPosition.x + j*parkingSlot.width, y: startPosition.y }, i);
        }
        j--;
    }
}

function draw200Gates(ctx, startPosition)
{
    var j = 0;
    for(let i = 249; i >= 200; i--)
    {
        if(i != 222)
        {
            drawParkingPlace(ctx, { x: startPosition.x + j*parkingSlot.width, y: startPosition.y }, i);
        }
        j--;
    }
}

building.js:

function drawBuildingShape(ctx, position)
{
    //Główna bryła budynku
    ctx.beginPath();
    const leftFingerLength = 65*parkingSlot.width; //Wcześniej 300
    const unloadingAreaWidth = leftFingerLength - 50 * parkingSlot.width - parkingSlot.length - 2;//Wcześniej 80.0
    const unloadingAreaLength = 41 * parkingSlot.width;
    const fingersWidth = (unloadingAreaLength - 8 * parkingSlot.width - 2 * parkingSlot.length)/2;
    const rightFingerLength =  unloadingAreaWidth + 66 * parkingSlot.width + parkingSlot.length + 10;
    var startPosition = {
        x: position.x - (rightFingerLength/2),
        y: position.y + (unloadingAreaLength/2)
    };
    ctx.moveTo(startPosition.x, startPosition.y);//Róg z biurem
    ctx.lineTo(startPosition.x + rightFingerLength, startPosition.y);//Dolna prawa krawędź frachtu
    ctx.lineTo(startPosition.x + rightFingerLength, startPosition.y - fingersWidth);//Górna prawa krawędź frachtu
    ctx.lineTo(startPosition.x + unloadingAreaWidth, startPosition.y - fingersWidth);//Róg przy 601
    ctx.lineTo(startPosition.x + unloadingAreaWidth, startPosition.y - unloadingAreaLength + fingersWidth);//Róg przy 401
    ctx.lineTo(startPosition.x + leftFingerLength, startPosition.y - unloadingAreaLength + fingersWidth);//Dolna prawa krawędź lewego fingera
    ctx.lineTo(startPosition.x + leftFingerLength, startPosition.y - unloadingAreaLength);//Górna prawa krawędź lewego fingera
    ctx.lineTo(startPosition.x, startPosition.y - unloadingAreaLength);//Róg przy 700
    ctx.lineTo(startPosition.x, startPosition.y)
    ctx.fillStyle = "lightblue";
    ctx.strokeStyle = "grey";
    ctx.fill();
    ctx.stroke();

    //Biuro HI
    ctx.beginPath();
    ctx.rect(startPosition.x - parkingSlot.length, startPosition.y, rightFingerLength - parkingSlot.width * 76 - 0.5 * parkingSlot.width, parkingSlot.length + 5);
    ctx.fillStyle = "lightblue";
    ctx.strokeStyle = "grey";
    ctx.fill();
    ctx.stroke();

    //Biuro fracht
    ctx.beginPath
    ctx.rect(startPosition.x + rightFingerLength, startPosition.y, 50, -fingersWidth);
    ctx.fillStyle = "lightblue";
    ctx.strokeStyle = "grey";
    ctx.fill();
    ctx.stroke();
    

    //Teren fracht
    ctx.beginPath
    ctx.rect(startPosition.x + rightFingerLength - 10, startPosition.y - 5, - parkingSlot.width * 27 + 10, -fingersWidth + 10);
    ctx.stroke();
    ctx.fillStyle = "grey";
    ctx.fill();

    return {
        topStart: {
            x: startPosition.x, 
            y: startPosition.y - unloadingAreaLength
        },
        inTopStart: {
            x: startPosition.x + leftFingerLength - parkingSlot.width,
            y: startPosition.y - unloadingAreaLength + fingersWidth
        },
        middleStart: {
            x: startPosition.x + unloadingAreaWidth, 
            y: startPosition.y - fingersWidth 
        },
        unloadingStart: {
            x: startPosition.x - parkingSlot.length,
            y: startPosition.y - unloadingAreaLength + parkingSlot.width
        },
        topFreightStart: {
            x: startPosition.x + rightFingerLength - parkingSlot.width - 10,
            y: startPosition.y - fingersWidth - parkingSlot.length
        },
        rightFingerStart: {
            x: startPosition.x + rightFingerLength - 27*parkingSlot.width - 10,
            y: startPosition.y - fingersWidth - parkingSlot.length
        },
        bottomFreightStart: {
            x: startPosition.x + rightFingerLength - parkingSlot.width - 10,
            y: startPosition.y
        },
        rightFingerBottomStart: {
            x: startPosition.x + rightFingerLength - 28*parkingSlot.width - 10,
            y: startPosition.y
        }
    };
}

Vite Build Fails with ‘Failed to Resolve src/indexReact.js’ Error in React Project

vite v6.2.0 building for production…
file:///C:/Users/abcd/project/node_modules/vite/dist/node/chunks/dep-ByPKlqZ5.js:41876
new Error(Failed to resolve src/indexReact.js from C:/Users/abcd/project/public/index.html)

Error: Failed to resolve src/indexReact.js from C:/Users/abcd/project/public/index.html
at file:///C:/Users/abcd/project/node_modules/vite/dist/node/chunks/dep-ByPKlqZ5.js:41876:27

Node.js v18.20.6

Project Structure is as follows

project/
├── node_modules/
├── public/
│   └── index.html
├── src/
│   ├── reactApp.jsx
│   ├── indexReact.jsx
│   └── ...
├── vite.config.js
├── package.json
└── ...

index.html codes

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="/src/indexReact.jsx"></script> <!-- Ensure this path is correct -->
</body>
</html>

indexReact.jsx codes

import React from 'react';
import { createRoot } from 'react-dom/client';
import ReactApp from './reactApp.jsx'; // Ensure this import is correct

const container = document.getElementById('root');
const root = createRoot(container);

root.render(<ReactApp />);

vite.config.js code

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  root: 'public',
  base: '/',
});

What I’ve Tried:

Ensured the path in index.html correctly points to indexReact.jsx.

Updated the file extensions from .js to .jsx for React components.

Cleared caches and reinstalled dependencies multiple times.

Verified the project structure and the existence of all files.

Project Environment:

Node.jsv18.20.6
Vite v6.2.0
React 18
Windows 10 2025

Development Server:
The Vite development server runs without issues, but the error occurs during the production build.

Console Errors:
No additional errors appear in the browser console during development.

Previous Build Tools:
The project was recently migrated from Webpack to Vite. Necessary changes were made to configuration files and package.json scripts.

Node Modules:
I have deleted and reinstalled the node_modules directory multiple times to ensure no old configurations or dependencies are causing conflicts.

Dependencies:
Key dependencies include:

  • “react”: “18.3.1”
  • “react-dom”: “18.3.1”
  • “vite”: “6.2.0”
  • “@vitejs/plugin-react”: “^3.0.0”

Despite the said efforts, the error persists. Any insights or suggestions on how to resolve this issue would be greatly appreciated!

Also, this maybe a known issue on stackoverflow but despite my efforts I couldn’t find a solution thus had to open a new question.

Showing error Uncaught ReferenceError: Cannot access ‘NavBar’ before initialization

<template>
    <nav class="navbar navbar-expand-lg bg-body-tertiary">
        <div class="container-fluid">
        <router-link class="navbar-brand" to="/">QUIZ APP</router-link>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li v-if="user" class="nav-item">
                    <router-link class="nav-link active" aria-current="page" to="/">Hi {{ user.name }}</router-link>
                </li>
                <li v-if="!authorized" class="nav-item">
                    <router-link class="nav-link" to="/login">Login</router-link>
                </li>
                <li v-if="!authorized" class="nav-item">
                    <router-link class="nav-link" to="/register" >Register</router-link>
                </li>
                <li v-if="authorized" class="nav-item">
                    <a class="nav-link" href="#" @click="logout">Logout</a>
                </li>
                <li>
                    <router-link class="nav-link" to="/SubjectCard">Subjects</router-link>
                </li>
                </ul>
            </div>
        </div>
    </nav>
</template>

<script>
import userMixin from '@/mixins/userMixin';
import SubjectCard from '@/views/SubjectCard.vue';
export default {
    name: 'NavBar',
    mixins: [userMixin],
    components: {
        SubjectCard
    }
}
</script>

This is my NavBar.vue component. I have used this component in SubjecCard component.

<template>
    <div>
        <NavBar/>
        <div class="container mt-5">
        <div class="row">
            <div class="col-md-4 mb-4" v-for="subject in subjects.subject" :key="subject.subject_id">
                <div class="card w-200">
                    <div class="card-body">
                        <div class="card-header  text-center ">
                            <h4>{{ subject.subject_name }}</h4>
                        </div>
                        <table class="table table-striped text-center table-bordereed">
                            <thead>
                                <tr>
                                    <th scope="col">Chapter Name</th>
                                    <th scope="col">Number of questions</th>
                                    <th scope="col">Remarks</th>
                                </tr>
                            </thead>
                                <tbody>
                                    <tr v-for="chapter in subjects.chapter" :key="chapter.chapter_id">
                                        <td v-if="subject.subject_id==chapter.subject_id">{{chapter.chapter_name}}</td>
                                        <td v-if="subject.subject_id==chapter.subject_id">0</td>
                                        <td v-if="subject.subject_id==chapter.subject_id">
                                            <div class="btn-group">
                                                <button class="btn btn-danger" @click="deleteChapter(chapter.chapter_id)">Delete</button>
                                                <EditChapter :id="chapter.chapter_id"  :editModalId="`Modal-${chapter.chapter_id}`" :run="getSubjects" />
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                        </table>
                    </div>
                    <div class="card-footer">
                        <div class="btn-group">
                            <button class="btn btn-delete text-center" @click="deleteSubject(subject.subject_id)">Delete</button>
                            <CreateChapter :id="subject.subject_id"  :modalId="`exampleModal-${subject.subject_id}`" :func="getSubjects" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <CreateSubject/>
    </div>
    </div>
</template>


<script>
import NavBar from '@/components/NavBar.vue';
import CreateSubject from '@/views/CreateSubject.vue';
import CreateChapter from '@/views/CreateChapter.vue';
import EditChapter from '@/views/EditChapter.vue';
export default {
    components: {
        NavBar,
        CreateSubject,
        CreateChapter,
        EditChapter,
    },
    data() {
        return {
            subjects: {
                subject: [],
                chapter: []
            }
        }
    },
    mounted() {
        this.getSubjects()
    },
    methods: {
        async getSubjects() {
            try {
                let response = await fetch('http://localhost:5000/get_subject',{
                    methods: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
                    }
                });
                const data = await response.json();
                console.log(data);
                if(response.ok) {
                    this.subjects = data
                } else {
                    alert(data.error)
                }
            } catch (error) {
                console.log(error)
            }
        },
    }
}
</script>

When i run SubjectCard component it shows error SubjectCard.vue:56 Uncaught ReferenceError: Cannot access ‘NavBar’ before initialization.

I want know why it is showing this error when i run the code.

I want to know why it is showing this error

Puppeteer executing the first click action in an array immediately, regardless of delay

I’m facing a seriously weird issue with puppeteer, running on Chrome.

I have an array of click actions I want to execute on a webpage, which has a pdf.js based slideshow. Each action consists of information on whether you are navigating to the next or previous slide, and what is the delay of said action in milliseconds. I’m also recording the whole thing.

The problem is that for some reason the first action is always immediately executed regardless of delay. Actions after the first behave as expected.

Things I have tried to no success:

  • Awaiting a timeout between actions.
  • Trying to click with vanilla JS using page.evaluate and waiting inside.
  • Using the built-in delay arg of puppeteer click() function and awaiting the actions
  • Firing random click event before the actual events
  • Updating puppeteer to its latest version
  • Putting random extra actions at the beginning of the actions array
  • Putting a hardcoded delay value into the click

Now I’m wondering that could this be a bug with puppeteer or chromium itself?

Below the current code

export const makeSlideshowVideo = async (
  output_file: string,
  actions: slide_change[],
  url: string,
  webcamLength: number
) => {
  try {
    const executablePath = await chromium.executablePath(
      "https://my-cdn.s3.eu-north-1.amazonaws.com/chromium-v132.0.0-pack.tar"
    );

    const browser = await puppeteer2.launch({
      executablePath,
      args: [
        `--window-size=${VIDEO_WIDTH},${VIDEO_HEIGHT}`,
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-gpu", // Disable GPU hardware acceleration
        "--disable-dev-shm-usage", // Use /tmp instead of /dev/shm
        "--no-zygote", // Disable zygote process for sandboxing
        // We have to disable security features, so that the browser can load pdf.js from CDN
        // TODO: this is not a safe solution, but might be the fastest fix for now.
        "--disable-web-security",
        "--allow-running-insecure-content",
      ],
      defaultViewport: { width: VIDEO_WIDTH, height: VIDEO_HEIGHT },
    });

    const page = await browser.newPage();

    await page.goto(url);

    // Wait for the slideshow to load
    await sleep(2000);

    const prevBtn = await page.$("#prev");
    const nextBtn = await page.$("#next");

    if (!prevBtn || !nextBtn) {
      throw new Error("No buttons found on the page");
    }

    // Set up the screen recorder
    const recorder = new PuppeteerScreenRecorder(page, recordConfig);

    await recorder.start(output_file);

    let prev = actions[0];
    await sleep(prev.elapsed_millisec);

    for (const next of actions) {
      const delay = next.elapsed_millisec - prev.elapsed_millisec;

      if (next.change_event === change_event.NEXT) {
        await nextBtn.click({ delay: delay });
      } else {
        await prevBtn.click({ delay: delay });
      }

      prev = next;
    }

    await sleep(webcamLength - (prev?.elapsed_millisec ?? 0));

    await recorder.stop();

    return output_file;
  } catch (error) {
    console.error((error as Error).message);
  }
};

Thank for the help!

Webpack JS code loading but not executing on external domain

I have a Rails app, in which I built an embeddable widget. The setup is as follows:

app/views/widgets/review/show.js.erb:

<%
  widget_data = @response_object.serializable_hash
  answers = widget_data[:answers]

  data = {
    target_name: "",
    content_identifier: "abc",
    answers: answers.map do |answer|
      {
        # ... map answers
      }
    end
  }

  pack_url = asset_pack_path("review_widget.js")
  public_path = Rails.root.join("public", pack_url.sub(/^//, ""))
  compiled_js = File.read(public_path) if File.exist?(public_path)

  css_url = asset_pack_path("review_widget.css")
  public_css_path = Rails.root.join("public", css_url.sub(/^//, ""))
  widget_css = File.read(public_css_path) if File.exist?(public_css_path)
  safe_css = widget_css.to_s.gsub("r", "").gsub("n", "\n").gsub('"', '"')
%>

(function() {
    <%# if Rails.env.production? %>
      const style = document.createElement('style');
      style.textContent = `
        <%= safe_css %>
      `;
      document.head.appendChild(style);
    <%# end %>

    window.localizedStrings = <%= I18n.t("widgets.reviews", default: {}).to_json.html_safe %>;
    window.reviewWidgetData = <%= data.to_json.html_safe %>;

    <%= compiled_js.html_safe if compiled_js.present? %>
})();

app/javascript/packs/review_widget.ts:

import { initReviewWidget } from "../review_widget/base"

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initReviewWidget);
} else {
  initReviewWidget();
}

app/javascript/review_widget/base.ts

import '../styles/review_widget.scss';

// more functions ...

export function initReviewWidget() {
  // call some functions etc...
  
  console.log('widget initialized');
}

HTML file for testing purposes:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Widget Test</title>
</head>
    <body>
    <h1>Testing the Widget</h1>
    <!-- The widget will be injected into the body -->
    <div id="#our-unique-widget-id"></div>
    <script type="text/javascript">
      (function() {
        const script = document.createElement('script');
        script.src = "http://localhost:5006/widgets/reviews.js?content_identifier=30a4d762e86596005b00b66c7b252fb4&locale=en";
        script.async = true;
        document.head.appendChild(script);
      })();
    </script>
    </body>
</html>

Local server is running at localhost:5006 and server the content at /widgets/reviews.js.
If the <div id="#our-unique-widget-id"></div> <script...> are in a page/file that are part of the same rails server, the JS works and a widget is rendered.

If we have this deployed to our staging server, where instead of localhost:5006 we set it to a CloudFront instance URL (which gets reviews.js from the staging server), it works too.

However, when the script is embedded anywhere that is not the server where it’s served from, it does not work.

This is the response of the reviews.js?... request:

(function() {
    const style = document.createElement('style');
    style.textContent = `
        :root {
        }
      `;
    document.head.appendChild(style);

    window.userDefinedFonts = [];
    window.localizedStrings = {
        "reviews_plural": "reviews",
        "button_write_review": "Leave a review"
    };
    window.reviewWidgetData = {
        // ... review data json
    };

    "use strict";
    (self["webpackChunkour_app_name"] = self["webpackChunkour_app_name"] || []).push([["review_widget"], {

        /***/
        "./app/javascript/packs/review_widget.ts": /*!***********************************************!*
  !*** ./app/javascript/packs/review_widget.ts ***!
  ***********************************************/
        /***/
        (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

            __webpack_require__.r(__webpack_exports__);
            /* harmony import */
            var _review_widget_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../review_widget/base */
            "./app/javascript/review_widget/base.ts");
            /* provided dependency */
            var __react_refresh_utils__ = __webpack_require__(/*! ./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js */
            "./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js");
            __webpack_require__.$Refresh$.runtime = __webpack_require__(/*! ./node_modules/react-refresh/runtime.js */
            "./node_modules/react-refresh/runtime.js");

            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', _review_widget_base__WEBPACK_IMPORTED_MODULE_0__.initReviewWidget);
            } else {
                (0,
                _review_widget_base__WEBPACK_IMPORTED_MODULE_0__.initReviewWidget)();
            }

            var $ReactRefreshModuleId$ = __webpack_require__.$Refresh$.moduleId;
            var $ReactRefreshCurrentExports$ = __react_refresh_utils__.getModuleExports($ReactRefreshModuleId$);

            function $ReactRefreshModuleRuntime$(exports) {
                if (false) {
                    var testMode, errorOverlay;
                }
            }

            if (typeof Promise !== 'undefined' && $ReactRefreshCurrentExports$ instanceof Promise) {
                $ReactRefreshCurrentExports$.then($ReactRefreshModuleRuntime$);
            } else {
                $ReactRefreshModuleRuntime$($ReactRefreshCurrentExports$);
            }

            /***/
        }
        ),

        /***/
        "./app/javascript/review_widget/base.ts": /*!**********************************************!*
  !*** ./app/javascript/review_widget/base.ts ***!
  **********************************************/
        /***/
        (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

            __webpack_require__.r(__webpack_exports__);
            /* harmony export */
            __webpack_require__.d(__webpack_exports__, {
                /* harmony export */
                initReviewWidget: function() {
                    return /* binding */
                    initReviewWidget;
                }/* harmony export */
            });
            /* harmony import */
            var _styles_review_widget_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../styles/review_widget.scss */
            "./app/javascript/styles/review_widget.scss");
            /* provided dependency */
            var __react_refresh_utils__ = __webpack_require__(/*! ./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js */
            "./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js");
            __webpack_require__.$Refresh$.runtime = __webpack_require__(/*! ./node_modules/react-refresh/runtime.js */
            "./node_modules/react-refresh/runtime.js");

            // more functions ...

            function initReviewWidget() {
                // call some functions etc...
                // Select element #our-unique-widget-id and add some content...

                console.log('widget initialized');
            }

            var $ReactRefreshModuleId$ = __webpack_require__.$Refresh$.moduleId;
            var $ReactRefreshCurrentExports$ = __react_refresh_utils__.getModuleExports($ReactRefreshModuleId$);

            function $ReactRefreshModuleRuntime$(exports) {
                if (false) {
                    var testMode, errorOverlay;
                }
            }

            if (typeof Promise !== 'undefined' && $ReactRefreshCurrentExports$ instanceof Promise) {
                $ReactRefreshCurrentExports$.then($ReactRefreshModuleRuntime$);
            } else {
                $ReactRefreshModuleRuntime$($ReactRefreshCurrentExports$);
            }

            /***/
        }
        ),

        /***/
        "./app/javascript/styles/review_widget.scss": /*!**************************************************!*
  !*** ./app/javascript/styles/review_widget.scss ***!
  **************************************************/
        /***/
        (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

            __webpack_require__.r(__webpack_exports__);
            // extracted by mini-css-extract-plugin

            /***/
        }
        )

    }, /******/
    function(__webpack_require__) {
        // webpackRuntimeModules
        /******/
        var __webpack_exec__ = function(moduleId) {
            return __webpack_require__(__webpack_require__.s = moduleId);
        }
        /******/
        __webpack_require__.O(0, ["vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-861caa"], function() {
            return __webpack_exec__("./node_modules/@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js"),
            __webpack_exec__("./node_modules/@pmmmwh/react-refresh-webpack-plugin/client/ErrorOverlayEntry.js?sockProtocol=http"),
            __webpack_exec__("./app/javascript/packs/review_widget.ts");
        });
        /******/
        var __webpack_exports__ = __webpack_require__.O();
        /******/
    }
    ]);
    //# sourceMappingURL=review_widget.js.map
}
)();

Any console.log('') I add in show.js.erb gets logged in the console, logging I add in the .ts files does not. With breakpoints in the .js response I can get to (self["webpackChunkour_app_name"] = self["webpackChunkour_app_name"] || []).push([["review_widget"], {, but not anything after that.

config/webpack/environment.js:

const path = require('path');
const { environment } = require('@rails/webpacker')
const webpack = require('webpack');

const customConfig = {
  optimization: {
    sideEffects: false
  },
  resolve: {
    alias: {
      '@components': path.resolve(__dirname, '../../app/javascript/components'),
      '@utils': path.resolve(__dirname, '../../app/javascript/utils'),
    },
  },
};

environment.config.merge(customConfig);

environment.loaders.prepend('sass', require('./loaders/sass'))

environment.loaders.append('typescript', {
  test: /.tsx?$/,
  use: [
    {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env', '@babel/preset-react'],
      },
    },
    'ts-loader',
  ],
  exclude: /node_modules/
});

environment.plugins.append('DefinePlugin', new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
}));

module.exports = environment

config/webpack/development.js:

process.env.NODE_ENV = process.env.NODE_ENV || 'development'

const webpackConfig = require('./base')
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')

if (!webpackConfig.plugins) {
  webpackConfig.plugins = [];
}

if (process.env.NODE_ENV === 'development') {
  webpackConfig.plugins.push(new ReactRefreshWebpackPlugin())
}

const finalWebpackConfig = {
  ...webpackConfig,
  devServer: {
    ...webpackConfig.devServer,
    hot: true,
    liveReload: false,
  },
};

// Log the final Webpack configuration
console.log('Webpack configuration:', JSON.stringify(finalWebpackConfig, null, 2))

module.exports = finalWebpackConfig

config/webpack/base.js:

const { webpackConfig, merge } = require('@rails/webpacker')
const webpack = require('webpack')
const customConfig = require('./custom')
webpackConfig.plugins.push(
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    jquery: 'jquery',
  })
)


module.exports = merge(webpackConfig, customConfig)

The output .js seems to include:

  • ./app/javascript/packs/review_widget.ts
  • ./app/javascript/review_widget/base.ts
  • etc.

I am not sure anymore what the issue can be. Looking at the compiled js it looks like it’s defining functions but never calling it. Or that it uses relative (to project) paths that of course don’t work outside of that.

The idea is that this can be embedded on external websites.

Firebase v2 Database Triggers not able access parent data from within

I’ve been trying to get parent data from within a Realtime Database onValueCreated trigger, however it seems to not be working no matter how I try to resolve the promise needed to fetch the data.

Here’s my code:

import {onValueCreated} from "firebase-functions/v2/database";
import * as admin from "firebase-admin";

if (admin.apps.length === 0) {
  admin.initializeApp();
}


export const forceTimeExtensionVote = onValueCreated({ref: "/matches/{matchId}/timeExtensionVoteEnded", region: "europe-west1"}, async (event) => {
  console.log("Force Time Extenion Vote running...");
  return await event.data.ref.parent?.ref.once("value").then((snapshot) => {
    // handle votes outcome for time extension
    console.log("Get parent data", snapshot.val());
  }).catch((error) => {
    console.log(error);
    throw error;
  });
});

Even if I remove the async/await and just return the promise, nothing is logged out at that ‘Get parent data’ log

Firefox 135.0.1 shows “Security Error: Content at someurl may not load data from blob:anotherurl when try download crossorigin image by canvas

Firefox 135.0.1 show “Security Error: Content at https://someurl may not load data from blob:https://anotherurl when I try download a crossorigin image by using canvas.

I’m writing a userscript to download images from a website domain a , which the image is at domain b, with access-control-allow-origin: * .

A normal crossOrigin a-link can’t use the download attribute because it would be ignored and the image would be opened in new tab.

I made a script (showing below) and it worked very fine, until a recent update from firefox broke it?

I test it on Firefox ESR 115 and my script is still working on it. Sorry I don’t have another environment to install another Firefox.

function getCrossOriginImage(button, currentTitle) {
    const img = new Image();
    const imageUrl = button.parentNode.querySelector('img').src;
    img.crossOrigin = 'anonymous';

    console.log(button);    //showing as expected: <a class="imagelink-nowatermark" style="white-space: break-space…: 0px; cursor: pointer;">
    console.log(imageUrl);  //showing as the expected image url
    console.log(img);   //showing: <img crossorigin="anonymous">

    img.onload = function() {

        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);

        const timeStr = getYmdHMS();
        const imageName = currentTitle + '-' + timeStr;

        canvas.toBlob(function(blob) {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = imageName + '.png';
            console.log(canvas);    //<canvas width="1024" height="768">
            console.log(a);     //<a href="blob:someurl" download="filename-20250304210048.png">
            console.log(a.href.toString());     //blob:https://someurl/b16b897f-6bb8-429a-8e22-576048a5acd5


            setTimeout(() => a.click(), 1000);      //Security Error: Content at https://someurl/chat/1689617777176578 may not load data from blob:https://someurl/b16b897f-6bb8-429a-8e22-576048a5acd5.
            setTimeout(() => URL.revokeObjectURL(url), 100);

        });
    };

    img.onerror = function() {
        console.error('error');
        alert('error');
    };

    img.src = imageUrl;
}

I need help.

I don’t know why but the newest Firefox(135.0.1) refuse to work at a.click(). I don’t know how to fixed.

If I can’t use canvas to download crossorigin image anymore, is there any other ways to do it?