How to make private function in JavaScript [closed]

I want to make private function for my language interpreter .
problem is with that i have some variables and functions i want not to be executed by the user
for example

function run1(){
alert("1")
}
var name=0;
let exported= privaterun( ["run1()"] , function(){
  export=20
  console.log(name) // undefined 
  run1() // run1 is not defined 
},["export"] )
alert(exported.export);

this is a example what i want to implement this doesn’t needs to look like this but i want have that behavior
yeah i know it could be done by making javascript interpreter in javascript but that nonsense for me for example make for loop and to every variable and function name add _1
it will still be possible to skip it somehow by the user .
and and will not be able to use variables with _1

i need a function or example to do that i use



let system;

function sandbox_wrapper(

system2, gl, c5tx, ox, oy, mouseX, mouseY, screenX, screenY,screenW, screenH, mouseAction, state, win) { const system = { system2, gl, c5tx, ox, oy,

mouseX, mouseY, screenX, screenY,

screenW, screenH, mouseAction, state, win}; 

function runner(code) {

try {const sandboxedFn = new Function("sys", `with (sys) {${code}}`); sandboxedFn(system);} catch (e) {}

}

return {run: runner, }

}
system = sandbox_wrapper( 1, this.gl, c5tx, this.x, this.y, this.mouseX, this.mouseY, this.x,this.y ,this.w,this.h , this.mouseAction, this.state ,this);
system.run(parsedcode);

but this doesn’t prevent for executing global functions and editing global variables .
is there way to do that ??
i would

¿Cuál es la mejor práctica para manejar múltiples llamadas a APIs en React sin afectar el rendimiento? [closed]

Estoy desarrollando una aplicación web con React que necesita hacer varias llamadas a distintas APIs al mismo tiempo (por ejemplo, para cargar datos de usuario, estadísticas y configuraciones iniciales). Me preocupa que esto afecte el rendimiento general de la app o cause bloqueos al renderizar.

¿Qué buenas prácticas recomiendan para gestionar múltiples peticiones de forma eficiente?
He escuchado sobre el uso de Promise.all, React Query, useEffect con control de dependencias, pero me gustaría saber:

¿Cuál método prefieren y por qué?

¿Cómo evitan renderizados innecesarios?

¿Recomiendan alguna librería externa para este tipo de casos?

Cualquier consejo, ejemplo o experiencia es bienvenido.

AfterRendered Hook in Paged.JS

I am using paged.js together with Kirby CMS and p5.js. And it is working pretty well.

My Problem: I need to get informed when paged.js is finished rendering the page layout. There should be a hook for this:

https://pagedjs.org/documentation/10-handlers-hooks-and-custom-javascript/

Unfortunately, my JS Skills end here. I just can’t find a way to get this information. In the end, I would like to get a global boolean.

Thanks for any help!

On GitHub: https://github.com/TomoyasuAR/atomics

Persisting multiple differently filtered collections in VELO for a WIX site

I have a Wix site and on one page we need to have two repeaters which are populated by different sets from the same (tutors) collection (defined by gold and silver tags).

the problem is that Wix does not allow the repeaters to be filtered together by the same dropdown filters. Wix has said it can be done with VELO, which I have tried with the code below.

It works fine on load but when I try and filter it using the dropdown it returns the whole collection.

I think this is because the gold and silver filtering does not persist. I think this could be resolved by saving the filtered collection to gold and silver variables but I cant seem to get this to work

Any help gratefully received.

import wixData from "wix-data";

$w.onReady(function () {
  //console.log(wixData);

  loadGoldTutors();
  loadSilverTutors();

});

//  GOLD TUTORS
function loadGoldTutors() {
  wixData.query("TeamMembers")
    .eq("subscriptionType", "Gold")
    .find()
    .then((results) => {
      $w("#repeater1").data = results.items;
      $w("#repeater1").onItemReady(($item, itemData, index) => {
        $item("#imageX7").src = itemData.image;
        $item("#text76").text = itemData.title;
      });
    });
}

//  SILVER TUTORS
function loadSilverTutors() {
  wixData.query("TeamMembers")
    .eq("subscriptionType", "Silver")
    .find()
    .then((results) => {
      $w("#repeater2").data = results.items;
      $w("#repeater2").onItemReady(($item, itemData, index) => {
        $item("#text75").text = itemData.title;
      });
    });
}

Unknown timeout error when refetching a query

I am having a dumb moment. I use Tanstack Query and Ky in my app to make requests and inject jwt tokens in them. Every time a request hits a 403 error, the request gets resent after acquiring a new access token.

The annoying thing is when 403 occurs it shows a 403 error in the console originating from timeout.ts. And the stack goes through the whole request proccess from Ky to Tanstack Query and I don’t know here to handle it so I can just post ‘Getting new token’ to console instead of this error.

I tried checking response.status in const request in useInfiniteLogsQuery, tried ky’s beforeError hook and tinkered with the response in customKy but nothing seems to affect this error.

GET http://localhost:8080/api/v1/users/root/ 403 (Forbidden) timeout.ts:24

Here’s the QueryClient:

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PropsWithChildren, useState } from "react";

const QueryProvider = ({ children }: PropsWithChildren) => {
  const [queryClientInstance] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 1000 * 30,
            retry: false,
          },
        },
      })
  );

  return (
    <QueryClientProvider client={queryClientInstance}>
      {children}
    </QueryClientProvider>
  );
};

export default QueryProvider;

Here’s the custom ky instance I use:

import useAuth from "hooks/useAuth";
import ky from "ky";

export const useKy = () => {
  const { auth, setAuth, refreshToken } = useAuth();

  const customKy = ky.extend({
    prefixUrl: "api/v1",
    hooks: {
      beforeRequest: [
        async (request) => {
          if (auth)
            request.headers.set("Authorization", `Bearer ${auth.access_token}`);
        },
      ],
      afterResponse: [
        async (request, _, response) => {
          if (response.status === 403) {
            console.log(response);

            try {
              await refreshToken().then(({ access_token, username }) => {
                setAuth({ access_token, username });
                request.headers.set("Authorization", `Bearer ${access_token}`);
              });

              return ky(request);
            } catch (error) {
              throw new Error("Failed to refresh token: " + error);
            }
          }
        },
      ],
    },
    retry: {
      methods: ["get", "post"],
      limit: 3,
      statusCodes: [403],
    },
  });

  return { customKy };
};

One of the queries:

export const useInfiniteLogsQuery = () => {
  const { customKy } = useKy();
  return useInfiniteQuery({
    queryKey: ["infiniteLogs"],
    queryFn: async ({ pageParam }) => {
      const link = pageParam.split("api/v1/")[1];
      const resolvedLink = `${link}&resolved=false`;
      const request = await customKy.get<LogsResponse>(resolvedLink).json();

      return request;
    },
    initialPageParam: `api/v1/logs-list/json/?limit=25&offset=0`,
    getNextPageParam: (lastPage) => lastPage?.next,
  });
};

enter image description here

Map Disappears When Popup Opens Instead of Showing Behind It

I’m using react-map-gl to create a cluster map with popups that appear when users click on map points. When a popup is triggered, the map completely disappears instead of remaining visible underneath the popup as expected.
Here’s what’s happening:

  • The map displays correctly initially with clusters and points
  • When clicking on an unclustered point, the popup appears correctly positioned
  • However, when the popup opens, the entire map disappears from view
  • The popup exists alone at the bottom of the container

Here is my code :

const ClusterMap = ({
  data: dataId,
  container: Container,
  header = "Cluster Map",
  subHeader = "",
  exportData,
  detailsComponent,
  children,
  expand,
  DataStringQuery,
  ...props
}: VisualProps) => {
  const [popupInfo, setPopupInfo] = useState<PopupInfo | null>(null);
  const mapRef = useRef(null);
  const { data, loading } = useDataStoreData(dataId);
  const geoJsonData = useGeoJson(data);
  console.log("=====geoJsonData", geoJsonData);

  if (loading) {
    return <MapSkeleton />;
  }

  if (!geoJsonData) {
    return <div>No data available for this map</div>;
  }
  console.log("=====popupInfo", popupInfo);

  const firstItem = geoJsonData.features[0];
  const initialLatitude = firstItem.geometry.coordinates[1];
  const initialLongitude = firstItem.geometry.coordinates[0];
  // Define sourceId and layers after GeoJSON data is processed
  const sourceId = "clusters";
  const [clusterLayer, clusterCountLayer, unclusteredPointLayer] =
    createClusterLayers(sourceId);

  // Define mapchildren with GeoJSON data
  const mapchildren = (
    <>
      <Source
        id={sourceId}
        type="geojson"
        data={geoJsonData}
        cluster={true}
        clusterMaxZoom={14}
        clusterRadius={50}
      >
        <Layer {...clusterLayer} />
        <Layer {...clusterCountLayer} />
        <Layer {...unclusteredPointLayer} />
      </Source>

      {popupInfo && (
        <Popup
          longitude={popupInfo.lngLat[0]}
          latitude={popupInfo.lngLat[1]}
          closeButton={true}
          closeOnClick={false}
          onClose={() => {
            mapRef.current?.resize();
            setPopupInfo(null);
          }}
          anchor="bottom"
          offset={[0, -10]}
        >
          <div>{popupInfo.text}</div>
        </Popup>
      )}
    </>
  );

  const content = (
    <BaseMap
      {...props}
      data={geoJsonData}
      expand={expand}
      ref={mapRef}
      interactiveLayerIds={["unclustered-point"]}
      userOptions={{
        initialViewState: {
          latitude: initialLatitude,
          longitude: initialLongitude,
          zoom: 2, // adjust zoom as needed
        },
        onLoad: (map) => {
          console.log("==========map", map);
          if (map && map.target) {
            map.target.on("click", "unclustered-point", (e) => {
              e.preventDefault();
              if (e.features && e.features.length > 0) {
                const feature = e.features[0];
                console.log("Direct map click handler triggered", feature);

                const coordinates = feature.geometry.coordinates.slice();
                console.log("Coordinates:", coordinates);
                const title = `${feature.properties?.facility_name} : ${feature.properties?.keph_level}`;

                setPopupInfo({
                  lngLat: coordinates as [number, number],
                  text: title,
                });
              }
            });
          }

          // Call the original onLoad if it exists
          if (props.userOptions?.onLoad) {
            props.userOptions.onLoad(map);
          }
        },
      }}
    >
      {mapchildren}
    </BaseMap>
  );
  console.log("=============here", popupInfo, mapchildren);

  return Container ? (
    <Container
      header={
        DataStringQuery ? (
          <DataString visualName={DataStringQuery}>{header}</DataString>
        ) : (
          header
        )
      }
      subHeader={subHeader}
      exportData={exportData}
      detailsComponent={detailsComponent}
      expand={expand}
      infoTagContent={getInfoTagContents(children)}
      DataStringQuery={DataStringQuery}
      dataId={dataId}
    >
      {content}
    </Container>
  ) : (
    content
  );
};

I have tried :

  • Adding explicit height/width to the map container (distorts the layout)
  • Using different anchor positions for the popup
  • Removing custom styling from the popup
  • Using the offset property on the Popup

I’m not seeing any errors in the console, and the popup itself is rendering correctly – it’s just that the map underneath disappears.

Any help or recommendations will be appreciated, thanks

How Can ShadowRoot Elements in a Custom HtmlElement Data Table Be Accessed After Async Functions Complete?

I’ve created a working (mostly) custom EntityTable (entity-table) HtmlElement that successfully fetches and displays JSON data from a custom RESTful microservice in an HTML <table>.

enter image description here

From another code module (app.js) I want to select (and highlight) the first table row (<tr>), including the integer entity id value it contains in its first cell (<td>), and pass the row (as the default selected row) to a listener that will use the id to populate a second, related EntityTable.

But when I set a breakpoint in app.js only the ‘tableelements seem to exist in the EntityTable's ShadowRoot element, which was attached inopenmode in itsconstructor()`.

Developer Tools Sources Tab

Developer Tools Elements Tab

index.html

    <section id="definitions">
      <entity-table id="entitytypedefinition" baseUrl="http://localhost:8080/entityTypes/" entityTypeName="EntityTypeDefinition" whereClause="%22Id%22%20%3E%200" sortClause="%22Ordinal%22%20ASC" pageNumber="1" pageSize="20" includeColumns="['Id', 'LocalizedName', 'LocalizedDescription', 'LocalizedAbbreviation']" zeroWidthColumns="['Id']" eventListener="entityTableCreated"></entity-table>
    </section>

EntityTable.js

//NOTE: Copyright © 2003-2025 Deceptively Simple Technologies Inc. Some rights reserved. Please see the aafdata/LICENSE.txt file for details.

class EntityTable extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });

    console.log(`EntityTable constructor ends.`);
  }

  //NOTE: Called each time this custom element is added to the document, and the specification recommends that custom element setup be performed in this callback rather than in the constructor
  connectedCallback() {
    const link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', 'css/style.css');
    this.shadowRoot.appendChild(link);

    //TODO: Get live authentication token
    document.cookie = "Authentication=XXX";

    const table = document.createElement('table');

    console.log(`EntityTable connectedCallback() Explicit parent id: ${this.getAttribute('id')}`);
    table.setAttribute('id', this.getAttribute('id') + '-23456' || 'entitytypedefinition-34567')   //TODO: Generate and append a unique id
    table.setAttribute('class', 'entity-table');

    console.log(`EntityTable connectedCallback() Not fetching data yet!`);

    //TODO: Should this be put back into the constructor???
    //TODO: And should the event listener be added to the document or to the table???
    this.addEventListener(this.getAttribute('eventListener') || 'DOMContentLoaded', async () => {
      console.log('EntityTable connectedCallback() ' + this.getAttribute('eventListener') + ` event listener added.`);
      try {
        if ((this.getAttribute('eventListener') == 'entityTableCreated') || (this.getAttribute('eventListener') == 'entityTableRowClicked')) {
          const data = await fetchData(this.getAttribute('baseUrl') || 'http://localhost:8080/entityTypes/', this.getAttribute('entityTypeName') || 'EntityTypeDefinition', this.getAttribute('whereClause') || '%22Id%22%20%3E%20-2', this.getAttribute('sortClause') || '%22Ordinal%22%20ASC', this.getAttribute('pageSize') || 20, this.getAttribute('pageNumber') || 1);
          await displayData(data, table, this.getAttribute('includeColumns') || ['Id', 'EntitySubtypeId', 'TextKey'], this.getAttribute('zeroWidthColumns') || []);
        }
      }
      catch (error) {
        console.error('Error fetching data:', error);
      }
    });

    this.shadowRoot.appendChild(table);
    console.log(`EntityTable connectedCallback() Data fetched and displayed!`);
  }
}

customElements.define('entity-table', EntityTable)

async function fetchData( ...

async function displayData( ...

app.js

//NOTE: Copyright © 2003-2025 Deceptively Simple Technologies Inc. Some rights reserved. Please see the aafdata/LICENSE.txt file for details.

console.log(`app.js executing! No DOMContentLoaded listener added yet.`);

//NOTE: Constructors for both EntityTables defined in index.html are called here

//NOTE: "Wire up" the two EntityTables so that when a row is clicked in the first EntityTable, the data is sent to the second EntityTable
document.addEventListener('DOMContentLoaded', () => {
  const entityTableDefinitions = document.getElementById('entitytypedefinition');
  const entityTableAttributes = document.getElementById('entitytypeattribute');

  console.log(`app.js still executing! DOMContentLoaded listener now added to page.`);

  //NOTE: Populate the definitions table with data by adding custom listener and dispatching custom event
  const definitionsEvent = new CustomEvent('entityTableCreated', {
    detail: { entityTableDefinitions }
  });

  console.log(`app.js still executing! Dispatching entityTableCreated event ...`);
  entityTableDefinitions.dispatchEvent(definitionsEvent);

  const selectedRow = entityTableDefinitions.shadowRoot.innerHTML; //NOTE: Get the first row in the table
  //.querySelectorAll('tr').length; //NOTE: Get the first row in the table
  //.querySelectorAll('table')[0]
  //.querySelectorAll('tbody');
  //.querySelectorAll('tr')[0]; //NOTE: Get the first row in the table

  //NOTE: Populate the attributes table with data by adding custom listener and dispatching custom event
  const attributesEvent = new CustomEvent('entityTableRowClicked', {
    detail: { selectedRow }
  });

  console.log(`app.js still executing! Dispatching entityTableRowClicked event: ${selectedRow} ...`);
  entityTableAttributes.dispatchEvent(attributesEvent);

  //TODO: Add click event listener to each row in the first table??? (unless passing the EntityTable reference is sufficient)

});

I’ve tried moving the this.shadowRoot.appendChild(table) statement up just under the await displayData() in the EntityTable’s this.addEventListener() method and making it await, but this actually resulted in less elements (only the <link>) being available.

I suspect that the app.js code is continuing to execute while the fetchData() and `displayData() promise(s) are awaited, but I’m stuck on how to prevent this.

I’m not a front-end guy. Any help would be greatly appreciated.

Calling .NET ClearScript V8 “Object.defineProperty” method for my my custom class

My project uses ClearScript V8 engine, I defined my custom class TestElement which does not have any dynamicObject Class inherit in .Net.

as follow script does not call defineProperty for my custom TestElement class.

Is there any work around?

If I don’t use my custom Class TestElement, javacript’s Object.defineProperty call is sucess.

 console.log(testElement);
 try
 {
    console.log('calling defineProperty');
    Object.defineProperty(testElement, 'property1', {
   value: 42,
   writable: false
  });
     console.log('defineProperty called');
} catch(e)
{
 console.log('definProperty Error: ' + e.message);
}

Imported modules becoming undefined in TypeScript Firebase Functions

I’m using Firebase Functions in TS. When executing npm run-script build and starting the emulator, here’s what it throws:

TypeError: Cannot read properties of undefined (reading 'user')
    at Object.<anonymous> (/home/starleaf1/projects/moonhope-finance-web/functions/lib/auth/registration.js:9:42)

Here’s how the TS looks like:

import auth from 'firebase-functions/v1/auth'
import admin from 'firebase-admin'

const createUserProfile = auth.user().onCreate(async user => {
  const { uid, email, displayName } = user

  const userProfile = {
    uid, email, displayName, createdAt: admin.firestore.FieldValue.serverTimestamp(),
  }

  const userDoc = admin.firestore().collection("users").doc(uid)
  userDoc.set(userProfile, { merge: true })

  admin.firestore().collection("pockets").doc(`default-${uid}`).set({
    author: { uid, email, displayName },
    shared: false,
    createdAt: admin.firestore.FieldValue.serverTimestamp(),
  })
})

export { createUserProfile }

and here’s the JS that tsc spat out into the lib/auth/registration.js:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUserProfile = void 0;
const auth_1 = __importDefault(require("firebase-functions/v1/auth"));
const firebase_admin_1 = __importDefault(require("firebase-admin"));
const createUserProfile = auth_1.default.user().onCreate(async (user) => {
    const { uid, email, displayName } = user;
    const userProfile = {
        uid, email, displayName, createdAt: firebase_admin_1.default.firestore.FieldValue.serverTimestamp(),
    };
    const userDoc = firebase_admin_1.default.firestore().collection("users").doc(uid);
    userDoc.set(userProfile, { merge: true });
    firebase_admin_1.default.firestore().collection("pockets").doc(`default-${uid}`).set({
        author: { uid, email, displayName },
        shared: false,
        createdAt: firebase_admin_1.default.firestore.FieldValue.serverTimestamp(),
    });
});
exports.createUserProfile = createUserProfile;
//# sourceMappingURL=registration.js.map

Any idea what might be causing this?

Final composition of WebGLRenderingContext and CanvasRenderingContext2D inside the browser window

I have two transparent <canvas> elements, a regular 2d and a webgl and both are filled with the same semi-transparent color e.g. 0x0000ff80.

Now what finally is composited inside the browser window looks different for both, most likely because the webgl canvas uses premultiplied while the regular canvas straight alpha.

let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0,0,127,0.5)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas);

canvas = document.createElement("canvas");
ctx = canvas.getContext("webgl");
ctx.clearColor(0, 0, 0.5, 0.5);
ctx.clear(ctx.COLOR_BUFFER_BIT);
document.body.appendChild(canvas);

What I need though is that the regular canvas is composited like the webgl canvas.

If I’d know the background color of the browser window upfront, I could paint the whole canvas with it and set the globalCompositeOperation to hard-light before drawing my actual content.
e.g.

let canvas = document.createElement("canvas");
ctx = canvas.getContext("webgl");
ctx.clearColor(0, 0, 0.5, 0.5);
ctx.clear(ctx.COLOR_BUFFER_BIT);
document.body.appendChild(canvas);

canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255,255,255,1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "hard-light"
ctx.fillStyle = "rgba(0,0,127,0.5)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas);

But as I said I’d need to know the background color and the canvas loses it’s tranparency.

What else could I do?

How to get access to the local db file? [closed]

I built an application in NEXTJS with better-sqlite3

There is a file called list.db which is in the main folder
When I run npm run dev or npm run build on my computer
Everything works without any problems and I have access to the file to retrieve information from it

I uploaded the project to GITHUB and did DEPLOY via NETLIFY
And NETLIFY does the BUILD and then I try to log in to ther website and get an ERROR 505 error and I also saw that the list.db file does not exist at all in the main folder
So I put it in the public folder and uploaded it again to GITHUB and did DEPLOY again and now the file does exist in the main folder but I still get the same error
Could it be that NETLIFY does not have access to the DB file? For some reason?

You cannot put the DATA file in other folder such as PUBLIC or an internal folder within the APP FOLDER , just in the main folder like in the image .

enter image description here

I tried all sorts of places to put the file but it doesn’t work
I would appreciate help

What is the difference between arrow function and anonymous function? [duplicate]

I have created a function with jQuery for hiding some <p> elements on double click and, for some reason, when I use arrow function it doesn’t work but as soon as I put it in anonymous function it starts working and I wonder why.

Arrow function:

$('p').dblclick(()→{
    $(this).hide();
});

Anonymous function:

$('p').dblclick(function(){
    $(this).hide();
});

From my understanding the arrow function is a short hand for anonymous functions, there should ideally have no difference.
What am I missing here?

How to change the size of the slide to the left and right of the center?

I need to make it so that 5 slides of cards of N slides are displayed on the page. I know that there is Swiper.js for this, but I haven’t worked with it.

Card structure: image + content (card description)
When the slide is active (in the center), the content is displayed.
When the slide is inactive, the content is hidden and only the image remains
The slide in the center has dimensions of 320 pixels (width) by 536 pixels (height).
The first slide to the right and the first to the left of the center slide have a height of 200 pixels and a width of 200 pixels.
The second to the right and the second to the left, also from the center, have dimensions of 100 pixels.

Another difficulty is that the distance from slide to slide should be calculated automatically. The container size is 1200px. This container should fit 5 slides and occupy the space approximately equally.

No matter what I do, nothing works. Please help me figure it out. It would be great if you could explain it to me in more detail. Thank you very much.

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <img class="slider__img" src="" alt="">
      <div class="slider__content"></div>
    </div>
    <div class="swiper-slide">
      <img class="slider__img" src="" alt="">
      <div class="slider__content"></div>
    </div>
    <div class="swiper-slide">
      <img class="slider__img" src="" alt="">
      <div class="slider__content"></div>
    </div>
    <div class="swiper-slide">
      <img class="slider__img" src="" alt="">
      <div class="slider__content"></div>
    </div>
    ...
    <div class="swiper-slide">
      <img class="slider__img" src="" alt="">
      <div class="slider__content"></div>
    </div>
</div>

Is not a constructor error when calling a different class method in TypeScript file

I am calling a method named RefreshPatientList in details.ts and getting an error

Uncaught TypeError: n.Upsm.BatchOrderCS is not a constructor

batchordercommon.ts

namespace Fe.Upsm {
  export abstract class BatchOrderCommon extends OrderBase implements IObserver {
    RefreshPatientList = (isNewOrder: boolean) => {
      // refresh data
    }
  }
}

BatchOrderCS.ts

namespace Fe.Upsm {
  export class BatchOrderCS extends BatchOrderCommon {
    constructor() {
      super(Enums.CallingView.BatchOrderPartial);
    }

details.ts

namespace Fe.Upsm {
  export class PatientDetails implements IObserver {
    Cancel(_Name: string) {
      dataAccess.ajaxCall(function(data) {
        new Fe.Upsm.BatchOrderCS().RefreshPatientList(true); // Uncaught TypeError: n.Upsm.BatchOrderCS is not a constructor
      }
    }
  }
}

Drag and Drop Swap in cards is not working

here is my code, and i am trying to Drag a .card (which includes an image),Drop it onto another .card and swap their content so they switch places visually. But it is not happening and also not getting any error on console aswell. Can anyone please help what is the issue and help me in debugging it.

 const cards = document.querySelectorAll('.card');
    let dragSource = null;

    cards.forEach(card => {
      card.addEventListener('dragstart', handleDragStart);
      card.addEventListener('dragover', handleDragOver);
      card.addEventListener('dragenter', handleDragEnter);
      card.addEventListener('dragleave', handleDragLeave);
      card.addEventListener('drop', handleDrop);
      card.addEventListener('dragend', handleDragEnd);
    });

    function handleDragStart(event) {
      dragSource = event.target;
      event.target.classList.add('dragging');
      event.dataTransfer.effectAllowed = 'move';
      event.dataTransfer.setData('text/html', event.target.innerHTML);
    }

    function handleDragOver(event) {
      console.log("here handle dragover")
      event.preventDefault();  // Allow drop
      event.dataTransfer.dropEffect = 'move';
    }

    function handleDragEnter(event) {
      event.preventDefault();
      event.target.classList.add('over');
    }

    function handleDragLeave(event) {
      event.target.classList.remove('over');
    }

    function handleDrop(event) {
      event.preventDefault();
      if (dragSource !== event.target) {
        console.log("here dragsource")
        let sourceHTML = dragSource.innerHTML;
        dragSource.innerHTML = event.target.innerHTML;
        event.target.innerHTML = sourceHTML;
      }
      event.target.classList.remove('over');
    }

    function handleDragEnd(event) {
      cards.forEach(card => {
        card.classList.remove('dragging', 'over');
      });
    }
    body {
      font-family: 'Segoe UI', sans-serif;
      background: #fff;
      margin: 0;
      padding: 2rem;
      text-align: center;
    }

    h1 {
      font-size: 2.5rem;
      margin-bottom: 2rem;
    }

    .card-layout {
      display: flex;
      justify-content: center;
      gap: 24px;
      max-width: 900px;
      margin: 0 auto;
    }

    .columns {
      display: flex;
      flex-direction: column;
      gap: 24px;
      flex: 1;
      max-width: 400px;
    }

    .card {
      position: relative;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      cursor: pointer;
    }

    .card img {
      width: 100%;
      object-fit: cover;
      display: block;
    }

    .short img {
      height: 212px;
    }

    .tall img {
      height: 424px;
    }

    .label {
      position: absolute;
      bottom: -10px;
      left: 12px;
      right: 12px;
      background: white;
      padding: 10px 14px;
      border-radius: 12px;
      font-size: 0.95rem;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    }

    @media (max-width: 768px) {
      .card-layout {
        flex-direction: column;
        align-items: center;
      }

      .columns {
        width: 100%;
        max-width: none;
      }
    }

    .container {
      position: relative;
    }
 <div class="card-layout">
    <div class="columns">
      <div class="card short" draggable="true" id="card1">
        <img src="https://th.bing.com/th/id/OSK.lfza5rzxC7_2q_NiBAs7eOFy_tlKtYXE7_MlbLg5w-c?w=312&h=200&c=10&pid=placeholderpartnerid&rm=2" alt="Orca">
      </div>
      <div class="card short" draggable="true" id="card2">
        <img src="https://th.bing.com/th/id/OSK.xdZQLhtExuYJ2ifeEPTU27ZtSZqmI6x9yrTaxDYXJFM?w=312&h=200&c=10&pid=placeholderpartnerid&rm=2" alt="Cherry Blossoms">
      </div>
      <div class="card tall" draggable="true" id="card3">
        <img src="https://th.bing.com/th/id/OSK.9TAX6CjlBCGryO5ezgflDgvd6E2ZxHwvyLKth2QlNN8?w=312&h=424&c=10&pid=placeholderpartnerid&rm=2" alt="Sorrento">
      </div>
    </div>

    <div class="columns">
      <div class="card tall" draggable="true" id="card4">
        <img src="https://th.bing.com/th/id/OSK.QjOLP9EnwvAP8GGBUdti0W499AX1NUXm--uWCOYpDMg?w=312&h=424&c=10&pid=placeholderpartnerid&rm=2" alt="Ocean">
      </div>
      <div class="card short" draggable="true" id="card5">
        <img src="https://th.bing.com/th/id/OSK.xdZQLhtExuYJ2ifeEPTU27ZtSZqmI6x9yrTaxDYXJFM?w=312&h=200&c=10&pid=placeholderpartnerid&rm=2" alt="Mountains">
      </div>
      <div class="card short" draggable="true" id="card6">
        <img src="https://th.bing.com/th/id/OSK.xdZQLhtExuYJ2ifeEPTU27ZtSZqmI6x9yrTaxDYXJFM?w=312&h=200&c=10&pid=placeholderpartnerid&rm=2" alt="Desert">
      </div>
    </div>
  </div>