Is this the right way to create a Svelte 5 store with two-way binding to a Firebase Realtime db path?

This is how I used to do it in Svelte 4:

// $lib/firebase.ts
export function writableRealtimeStore<T>() {
  let unsubscribe: () => void = () => {}
  let objectRef: any

  const store = writable<T | null>(null)
  let storeSet = store.set

  return {
    subscribe: store.subscribe,
    set: (value: any) => {
      return set(objectRef, value)
    },
    update: () => {},
    setPath: (path: string) => {
      objectRef = ref(realtimeDB, path)
      unsubscribe()
      unsubscribe = onValue(objectRef, (snapshot) => {
        storeSet((snapshot.val() as T) ?? null)
      })
    },
  }
}

// $lib/stores.ts
export const myStore = writableRealtimeStore()

// routes/+page.svelte
<script lang="ts">
    import { myStore } from '$lib/stores'
    myStore.setPath('/books/<book_id>')
</script>

<input type="text" bind:value={myStore.bookName}

This store is reactive both ways – when the value in the DB changes, it updates the UI, and when the user updates the value of the input, the DB changes. I could access the properties of my DB object directly as myStore.bookName.

However with Svelte 5 I can’t get the same behavior of the store object:

// $lib/firebase.ts
export function createRealtimeStore<T>() {
    let unsubscribe = () => {}
    let store: { value: T | undefined } = $state({ value: undefined })
    let _ref: DatabaseReference

    return {
        get value(): T | undefined {
            return store.value
        },
        update: () => {
            if (_ref) set(_ref, store.value)
        },
        setPath: (path: string) => {
            _ref = ref(realtime, path)
            unsubscribe()
            unsubscribe = onValue(_ref, (snapshot) => {
                store.value = snapshot.val()
            })
        },
        unsubscribe,
    }
}

// $lib/stores.ts
export let myStore = createRealtimeStore()

// routes/+page.svelte
<script lang="ts">
    import { myStore } from '$lib/stores'

    myStore.setPath('/books/<book_id>')

    $effect(() => {
        if (project.value) {
            project.update()
        }
    })
</script>

<input type="text" bind:value={myStore.value.bookName}

Two problems:

  1. I must access the store’s props like myStore.value.bookName, instead of the cleaner myStore.bookName.
  2. The $effect rune must be in the page and not in the function that creates the store, because $effect can only be called during component initialization, otherwise you get an error.

Overall the Svelte 4 way of doing it was much cleaner and nice to work with and I refuse to believe that you can’t do the same thing with the new and supposedly improved store system.

All my previously working HTML pages are now showing errors with the meta tags. How can I fix this?

I’m encountering an issue with meta tags in my HTML template. My code was previously working fine, but now the meta tags are showing errors, and I’m not sure what’s causing it. Here’s a snippet of my template:

{{ define "DevicePage" }}
<!DOCTYPE html>
<html lang="tr">

{{ template "PublicHead" }}

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kullanıcı Yönetimi</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/css/iziToast.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.11.3/main.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/main.min.css" rel="stylesheet">
</head>

The errors appear under the tags, specifically and . This started happening across multiple pages, and I haven’t changed anything in the meta tags themselves.

I’m using this template with a Go backend, which includes parts like {{ define “DevicePage” }} and {{ template “PublicHead” }}. I’ve tried restarting my IDE and checking the syntax, but the errors persist.

Has anyone experienced similar issues, or does anyone have any ideas on what could be causing this?
screenshot of the error

Svelte 5: TypeError [Error]: entry.default.render is not a function

I am trying to upgrade a svelte app from version 3 to version 5. And I am running into this issue.

node:internal/event_target:1094
  process.nextTick(() => { throw err; });
                           ^
TypeError [Error]: entry.default.render is not a function
    at getMetadata (file:///.../project/.svelte-kit/output/server/chunks/entries.js:475:28)
    at file:///.../project/.svelte-kit/output/server/chunks/entries.js:491:45
    at Array.map (<anonymous>)
    at getEntries (file:///.../project/.svelte-kit/output/server/chunks/entries.js:491:18)
    at file:///.../project/.svelte-kit/output/server/entries/pages/about/_page.server.js:2:17
    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)
    at async Promise.all (index 3)
    at async analyse (file:///.../project/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js:66:16)
    at async MessagePort.<anonymous> (file:///.../project/node_modules/@sveltejs/kit/src/utils/fork.js:23:16)
Emitted 'error' event on Worker instance at:
    at [kOnErrorMessage] (node:internal/worker:326:10)
    at [kOnMessage] (node:internal/worker:337:37)
    at MessagePort.<anonymous> (node:internal/worker:232:57)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:820:20)
    at MessagePort.<anonymous> (node:internal/per_context/messageport:23:28)

Node.js v20.17.0

The faulty code block is below:

const getMetadata = (entryType, filepath, entry) => {
    return {
        ...
        content: entry.default.render().html, // <---
        ...
    }

entry is something like Object.entries(import.meta.glob('<regex>', { eager: true})).

How to order by number?

I think that is a very big problem for every coder since it can destroy every page but does someone know perhaps how to correct it? Someone trieing to order DOM elements by JQuery finds very fast that the algorythm does not really compare to the fullest.

So for example

divArr = $("a:has(.ads)")
function ab() {
        $(".paginate").hide()
        divArr.sort(function(a, b) {
                return $(a).find(".price1").text() > $(b).find(".price1").text() ? 1: -1;
        })
        $(".paginate").append(divArr)
        $(".paginate").fadeIn().slideDown('1032')
}
function ba() {
        $(".paginate").hide()
        divArr.sort(function(b, a) {
                return $(a).find(".price1").text() > $(b).find(".price1").text() ? 1: -1;
        })
        $(".paginate").append(divArr)
        $(".paginate").fadeIn().slideDown('1032')
}

One function is to order ascending and the other descending. But still, they don’t GET ordered by price only, if there are other numbers outside of the .price1 class DOM element.

Some elements get ordered by a string outside of that class. I don’t know why that is. Thx for any help.

I consider that a reason why it is logical to change to a CMS, that already has these functions and also orders them for the whole array that is paginated too.

Cypress test catching the wrong request

I’m trying to catch a request, but others are raised on the same page.

I want to get the second request, but apparently the third overwrites the intercept

 beforeEach(() => {
    cy.visit("/portal/grafico");
  });
  
it("Deve interceptar a requisição e verificar se ela é válida quando clicar no select do gráfico Percentual de municípios por faixa de matrículas em tempo integral e inse", () => {
    cy.wait(1000);
    cy.intercept({
      method: "GET",
      url: `${apiUrl}/api/distribuicao-municipio-faixa-matricula/?ano=2022`,
    }).as("apiRequest");

    cy.get('[data-testid="selectPrincipalGraficos"]').click();
    cy.get("ul.p-dropdown-items")
    .should("be.visible")

    .contains(
        "Percentual de municípios por faixa de matrículas em tempo integral e inse"
    )
    .should("be.visible")
    .click();

    cy.wait("@apiRequest").then((interception) => {
      if (interception.response) {
        expect(interception.response.statusCode).to.eq(200);
      }
    });
  });

enter image description here

webpack, export ‘default’ (imported as ‘x’) was not found in

I have 2 projects. One of them is written in typescript and is named tsproject. Other one is written in js and is named jsproject.

I builded the tsproject by using tspc -p tsconfig.json. The tsconfig.json is like this:

// tsproject/tsconfig.json
{
  ...,
  "compilerOptions": {
    ...,
    "target": "ES2018"
    "module": "commonjs",
    "outDir": "lib",
    ...,
  },
  ...    
}

After the building, I copied everything in the tsproject/lib folder to jsproject/src/libs/tsproject. I can use as

// jsproject/src/index.js
import { TsProjectClass } from '~/libs/tsproject'; // This class is exported as `export class TsProjectClass { ... }`

I use webpack in jsproject to build and here is the webpack.config.js file:

// jsproject/webpack.config.js
const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv').config();

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js',
  },
  externals: {
    ...
  },
  module: {
    rules: [
      {
        test: /.js?$/,
        exclude: /node_modules/,
        include: path.resolve(__dirname, 'src'),
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
  plugins: [new webpack.EnvironmentPlugin(Object.keys(process.env))],
};

module.exports = config;

However, when I build using Webpack I get this error:

WARNING in ./src/index.js 38:19-39
export 'default' (imported as 'TsProjectclass') was not found in './libs/tsproject' (possible exports: __esModule)

What am I missing?

Thanks for replies.

Which HTML tags and attributes should be allowed as user-input for an application to reduce risk of cross-site scripting exploits?

In a given scenario where users of an application can create note-content in Quill, what tags and attributes should be whitelisted in a policy file. I am using OWASP AntiSamy for sanitization.

I am not very familiar with JS or HTML and therefore unsure of what tags to whitelist.

I have included a list of some tags and attributes, but not sure if I am missing anything

        <tag name="b" action="validate"/>
        <tag name="i" action="validate"/>
        <tag name="u" action="validate"/>
        <tag name="em" action="validate"/>
        <tag name="mark" action="validate"/>
        <tag name="strong" action="validate"/>

        
        <tag name="p" action="validate"/>
        <tag name="br" action="validate"/>
        <tag name="ul" action="validate"/>
        <tag name="ol" action="validate"/>
        <tag name="li" action="validate"/>

       
        <tag name="a" action="validate">
            <attribute name="href" action="validate">
                <regexp-list>
                    <regexp value="^https?://.*"/>
                    <!-- other safe links -->
                </regexp-list>
            </attribute>
            <attribute name="title" onInvalid="remove"/>
            <attribute name="target" onInvalid="remove"/>
        </tag>

Properly setup mocking for pg-promose in express.js for supertests

I am using pg-promose inside its own module to initialise a connection to DB and then use that connection in my route modules or anywhere else its imported.

import pgPromise from 'pg-promise'

let psqlClient
const pgp = pgPromise({/* Initialization Options */ })
const connection = {
    connectionString: process.env.PSQL_URI || "postgres://postgres@postgresql:5432",
    max: process.env.PSQL_POOL_SIZE || 15
}
export const connectPSQL = async () => {
    try {
        psqlClient = pgp(connection);
    } catch (e) {
        console.error(`Error Connecting to DB: ${e}`);
    }
}


export const getPSQLClient = () => {
    return psqlClient;
};

export const getURL = () => {
    return process.env.PSQL_URI
}

This is a pretty simple module however I cannot seem to wrap my head around on how to mock it in a unit test for a specific route. Following guides like this one I am doing something simple like:

import request from 'supertest';
import express from 'express';
import { getPSQLClient } from "../clients/postgresql.js";
import {get as GETFoo} from '../routes/v1/foo/index.js';
import { jest } from '@jest/globals';

jest.mock("../clients/postgresql.js")

const app = express();

app.use(express.json());
app.use('/v1/foo/index.js', GETFoo);


describe('Sample Test', () => {
    it('should test that true === true', () => {
      expect(getPSQLClient).toHaveBeenCalledTimes(1);
    })
  })

But this is returning: Matcher error: received value must be a mock or spy function which seems like the mocking is not being done correctly.

What I ultimately want is to be able to mock query results since my route involves querying like:

 let result = await psqlClient.any(
            "SELECT * FROM goo WHERE id=$1 LIMIT 1",
            [req.params.rid]
        )

I just want to plug in my own mocked result

unable to generate pdf using jsreports in a linux VM

i was trying to generate pdf using jsreports in a server
but it’s keep on throwing the below error
enter image description here

i tried installing the necessary package i don’t know how to fix this error
the below screenshot is the logic which is used to generate the pdf
the package which im used is a jsreport-core which takes chrome-pdf as a receipe to generate pdf so I tried installing chromium and it’s necessary packages, but it’s throwing an error
this issue is only persisting in a azure vm
enter image description here

can’t seem to find a way to remove a value from an array in my firestore within a batched write

I am using javascript with CDN imports and I am trying to remove an element from an array within a batched write, however it seems that no matter what I try I keep getting errors with the most common being the following:
Uncaught (in promise) TypeError: FieldValue.arrayRemove is not a function

I use the following import for the firestore:

import { getFirestore, doc, getDoc, writeBatch, FieldValue } from "https://www.gstatic.com/firebasejs/11.0.1/firebase-firestore.js";

I have tried a couple of solutions, the ones I can remember I have here below (here ‘theirUIDsDocRef’ is the reference to the document with the array, ‘UIDs’ is the name of the array and ‘myUID’ is a variable containing my UID which I want to delete):

batch.update(theirUIDsDocRef, { "UIDs": FieldValue.arrayRemove(myUID) });

batch.update(theirUIDsDocRef, "UIDs", FieldValue.arrayRemove(myUID));

batch.update(theirUIDsDocRef, { UIDs: FieldValue.arrayRemove(MyUID) });

If there is anything else you might need to know, please ask.

How to Securely Redirect to a Dynamic Logout URL in Vue.js Without Causing an Open Redirect Vulnerability?

I’m working on a Vue.js application where we need to securely redirect users to a logout URL. This URL is dynamically set through environment variables (process.env.VUE_APP_LOGOUT), which changes based on the environment (e.g., development, staging, production).

logout() {
  window.location.href = process.env.VUE_APP_LOGOUT;
}

The Problem

Using a dynamic URL for redirection introduces an Open Redirect vulnerability, which can be exploited in phishing attacks if the URL is not properly validated. I want to ensure that this redirection only points to approved domains and does not expose our application to security risks.

Question

What is the best way to securely handle dynamic URL redirection in Vue.js for logout, without exposing the app to open redirect vulnerabilities? Is it secure to store URLs in an array within the project and validate them from there? Any recommended practices or security-focused solutions would be greatly appreciated!

How to Implement Step Validation with react-hook-form without Using Zod Resolver?

I’m working on a multi-step form in React using react-hook-form, and I want to validate each step before allowing the user to proceed. I’m currently using the trigger method for validation, but I keep getting undefined when I try to call it. I don’t want to use a Zod resolver for validation.
Here is a snippet of my current implementation:

const form = useForm({
    defaultValues: {
        company: "",
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        password: '',
        password_confirmation: '',
        country: '',
        messenger: '',
        messenger_id: '',
        city: '',
        street_address: '',
        state: '',
        zip_code: ''
    },
});

const handleNextStep = async () => {
    console.log(`Current step: ${step}`);

    let isValid = false;

    // Validate based on current step
    if (step === 0) {
        isValid = await form.trigger(['email', 'phone', 'messenger', 'messenger_id']);
    } else if (step === 1) {
        isValid = await form.trigger(['company', 'first_name', 'last_name', 'street_address', 'city']);
    } else if (step === 3 || (step === 2 && !hasQuestions)) {
        isValid = await form.trigger(['password', 'password_confirmation']);
    }

    console.log(`Form valid: ${isValid}`);

    if (isValid) {
        if (step < totalSteps - 1) {
            setStep((prevStep) => prevStep + 1);
        } else {
            form.handleSubmit(onSubmit)();
        }
    } else {
        console.log(`Please complete the current step before proceeding.`);
    }
};

When I call form.trigger, it always returns undefined, preventing me from performing step validation. I need to ensure that users cannot proceed to the next step without completing the current one.

1.Why am I getting undefined when calling form.trigger?
2.What is the correct way to implement step validation in react-hook-form without using a resolver like Zod?
3.Are there any best practices or common pitfalls to avoid when validating multi-step forms with react-hook-form?

Thank you for your help!

How to render a react functional component when instance variable of separate class instance changed?

I am trying the below code,

SubscriptionHandler.js

class SubscriptionHandler {
  constructor() {
    this.orderBooks = [];
  }
  
  recenterOrderBooks = () => {
    this.orderBooks.forEach((item, idx) => {
      // doing something
    });
  };
}

const subscriptionHandler = new SubscriptionHandler();

export default subscriptionHandler;

OrderBookHome.js

import subscriptionHandler from "../../services/SubscriptionHandler";

function OrderBookHome() {
   // some piece of code
   
   return (
     <Box display="flex" justifyContent="center">
    <AddOrderBookForm handleRecenter={subscriptionHandler.recenterOrderBooks}    />
    </Box>
   )

}

export default OrderBookHome;

AddOrderBookForm.js

function AddOrderBookForm({...otherstates, handleRecenter}) {
   // some piece of code
   
   return (
     ....code
     {condition &&
        <Button onClick={handleRecenter}> Recenter Orderbooks </Button>
     }          
     ....code
   )

}

export default AddOrderBookForm;

In this piece of code, whenever the button is clicked I want to rerender OrderBookHome component and display recent data of orderBooks from subscription handler. What is the correct way to do it?
I don’t want to create a separate instance of SubscriptionHandler in OrderBookHome.

Error message not displaying for all inputs

I am trying to add my error message and icon for all inputs that are invalid, however, it only works for the first input. What am i doing wrong? This is not my full solution just a piece of code that is not working, I intend to solve the rest on my own.

I tried using input.value to but that did not work either.

const input = document.querySelectorAll("input");

input.forEach((input) => {
  input.addEventListener("invalid", getErrorMsg);

  input.addEventListener("focus", removeErrorMsg);


})

function getErrorMsg(e) {
  const errorIcon = document.querySelector(".error-icon");
  const errorTxt = document.querySelector(".error-txt");
  errorIcon.classList.add("active");
  errorTxt.classList.add("active");

};

function removeErrorMsg(e) {
  const errorIcon = document.querySelector(".error-icon");
  const errorTxt = document.querySelector(".error-txt");
  errorIcon.classList.remove("active");
  errorTxt.classList.remove("active");
}
.inputDiv {
  position: relative;
  border: 1px solid transparent;
}

.error-icon {
  display: none;
  position: absolute;
  top: 18px;
  right: 30px;
}

.error-txt {
  display: none;
  color: var(--CLR-RED);
  font-style: italic;
  font-size: 0.8em;
  font-weight: var(--FW-BOLD);
  position: absolute;
  bottom: -10px;
  right: 0;
}

.error-icon.active,
.error-txt.active {
  display: block;
}
<form class="formContainer">
  <div class="inputDiv">
    <input class="input" type="text" id="firstName" name="firstName" placeholder="First Name" required>
    <img class="error-icon" src="images/icon-error.svg" alt="">
    <p class="error-txt">First Name cannot be empty</p>
  </div>

  <div class="inputDiv">
    <input class="input" type="text" id="lastName" name="lastName" placeholder="Last Name" required>
    <img class="error-icon" src="images/icon-error.svg" alt="">
    <p class="error-txt">Last Name cannot be empty</p>
  </div>

  <div class="inputDiv">
    <input class="input" type="email" id="email" name="email" placeholder="Email Address" required>
    <img class="error-icon" src="images/icon-error.svg" alt="">
    <p class="error-txt">Looks like this is not an email</p>
  </div>

  <div class="inputDiv">
    <input class="input" type="password" id="password" name="password" placeholder="Password" required>
    <img class="error-icon" src="images/icon-error.svg" alt="">
    <p class="error-txt">Password cannot be empty</p>
  </div>

  <button type="submit" class="freeTrialBtn">
  Claim your free trial 
</button>
</form>