Node.js projemde sürekli tekrar eden server hataları [closed]

Bir online sohbet uygulaması kodladım. Bu projede node.js kullandım ve glitch ile yayınladım. Ama yayınladığım glitch sayfasında mesaj atamıyordum ve sürekli “Sohbete Hoşgeldiniz” yazıyordu (Bunun nedeni uygulamaya giriş yapıldığında “Sohbete Hoşgeldiniz” yazdır diye bir kod yazmam). Daha sonra konsolu açtım ve bir sürü server hataları ile karşılaştım. Bu hataları ekstra olarak koydum. Anladığım kadarıyla server kapanıyor ve tekrar açılıyordu. Bu ise sürekli tekrar ediyordu. Bu hatayı nasıl düzeltebilirim? Cevap verirseniz sevinirim.

Sadece bir sohbet uygulaması kodlamak istedim ve böyle hatalarla karşılaştım. ChatGPT’ye de sordum ama çözemedim.

Transitioning SVG Line Position

document.addEventListener("DOMContentLoaded", (event) => {
  const hamburgerButtons = document.querySelectorAll('.hm-button');
  const hamburgerLines = [
    {
      closed: {
        x1: 13,
        x2: 37,
        y1: 13,
        y2: 13,
      },
      open: {
        x1: 13,
        x2: 37,
        y1: 37,
        y2: 13,
      }
    }, {
      closed: {
        x1: 13,
        x2: 37,
        y1: 25,
        y2: 25,
      },
      open: null,
    }, {
      closed: {
        x1: 13,
        x2: 37,
        y1: 37,
        y2: 37,
      },
      open: {
        x1: 13,
        x2: 37,
        y1: 13,
        y2: 37,
      }
    }
  ]

  const handleHamburgerClick = (event) => {
    const button = event.target.closest('.hm-button');
    const lines = button.querySelectorAll('line');
    if (!button.classList.contains('open')) {
      lines.forEach((line, idx) => {
        if (hamburgerLines[idx].open) {
          line.setAttribute('x1', hamburgerLines[idx].open.x1)
          line.setAttribute('y1', hamburgerLines[idx].open.y1)
          line.setAttribute('x2', hamburgerLines[idx].open.x2)
          line.setAttribute('y2', hamburgerLines[idx].open.y2)
        }
      });
      button.classList.add('open');
    } else {
      if (button.classList.contains('open')) {
        lines.forEach((line, idx) => {
          if (hamburgerLines[idx].closed) {
            line.setAttribute('x1', hamburgerLines[idx].closed.x1)
            line.setAttribute('y1', hamburgerLines[idx].closed.y1)
            line.setAttribute('x2', hamburgerLines[idx].closed.x2)
            line.setAttribute('y2', hamburgerLines[idx].closed.y2)
          }
        });
        button.classList.remove('open');
      }
    }
  };

  hamburgerButtons.forEach((button) => {
    button.addEventListener("click", handleHamburgerClick);
  });
});
.hm-button {
  width: 50px;
  height: 50px;
  cursor: pointer;
}

.hm-button.open .hm-line2 {
  stroke: none;
}

.hm-outline {
  x: 2px;
  y: 2px;
  width: 46px;
  height: 46px;
  rx: 4px;
  fill: none;
}

.hm-outline,
[class^="hm-line"] {
stroke-width: 4px;
stroke: black;
}

[class^="hm-line"] {
stroke-linecap: round;
transition: all 0.25s ease;
}
<svg class="hm-button" role="button">
  <rect class="hm-outline" />
  <line class="hm-line1" x1="13" x2="37" y1="13" y2="13" />
  <line class="hm-line2" x1="13" x2="37" y1="25" y2="25" />
  <line class="hm-line3" x1="13" x2="37" y1="37" y2="37" />
</svg>

I’m attempting to create a hamburger menu icon using SVG and its child elements as a way to teach myself, but I’m having trouble transitioning the line positions. The change in position is instant, rather than gradual.

What I’m trying to achieve is, the middle line disappearing, and the left point of the first and third lines swap to form an X when the svg is clicked. When it is clicked again, the lines move back and the middle one reappears. Transition doesn’t seem to work when changing the position of the lines, however.

Leaflet non-geographic map with a TileLayer

I’m working on using leaflet to render a large rectangular game map, so using a TileLayer is the only reasonable option. Unfortunately I’m having a devil of a time getting the 3 different coordinate systems (game, image, and leaflet) aligned in a reasonable way. There’s… something about this all that I’m not understanding despite having read many, many SO posts and various other sources of information about CRS.Simple, L.TileLayer, L.transformation, and etc.

Here’s roughly the code I’m working with:

// These values correspond to the bounds of the in-game map
const GAME_MIN_X = -2438281.4186383262;
const GAME_MIN_Y = -1129394.0806274635;
const GAME_MAX_X = 201600;
const GAME_MAX_Y = 504000;

// The size of the source image for the tiles
const IMG_MAX_X = 16384;
const IMG_MAX_Y = 5223;

// Maximum x/y values assuming a range starting at 0
const MAX_X = GAME_MAX_X - GAME_MIN_X;
const MAX_Y = GAME_MAX_Y - GAME_MIN_Y;

// Scale factor for the transformation, see https://gis.stackexchange.com/a/201037
const scaleX = 1 / (MAX_X / IMG_MAX_X);
const scaleY = 1 / (MAX_Y / IMG_MAX_Y);

const crs = L.extend(L.CRS.Simple, {
  transformation: L.transformation(
    scaleX,
    0,
    scaleY,
    0
  ),
});

var map = L.map('map', {
  crs,
  maxZoom: 6,
});

const tiles = L.tileLayer("https://patcavit.com/tiles/{z}/{y}/{x}.png", {
  errorTileUrl: "https://patcavit.com/tiles/blank.png",

  minNativeZoom: 0,
  maxNativeZoom: 6,
  noWrap: true,

  bounds: [
    // Using MAX_* shows a lot of blank tiles
    [MAX_Y, 0],
    [0, MAX_X],
    // Using GAME_MAX_* shows a lot of blank tiles
    // [ GAME_MAX_Y, 0 ],
    // [ 0, GAME_MAX_X ],
    // Using IMG_MAX_* leads to only one tile being shown
    // [ IMG_MAX_Y, 0 ],
    // [ 0, IMG_MAX_X ]
  ],
});

tiles.addTo(map);

map.setView([0, 0], 0);

Here’s a live, editable version

I suspect that there’s a small part of the transformation on the CRS or how I’m defining bounds on the TileLayer that is tripping up literally everything else, but I’m kind of at my wit’s ends here.

For context, the MAX_Y and MAX_X values are me trying to scope the range of my points to start from 0 because that seems to play better with the TileLayer bits, but that could just be me misunderstanding things. I’d love to not need it, as it makes turning game coordinates into map coordinates a tiny bit inconvenient.

React Testing Library: rerender creates a new component

I have this component that I am trying to test, that shows a dialog which accepts images to upload into the app:

import React from 'react';
import { Box, Typography, Dialog, DialogTitle } from '@mui/material';

import UploadBox from './UploadBox';


/**
 * An interface for uploading new images to the app.
 * 
 * @param {object} props Contains props passed to the component.
 * @param {boolean} props.open Controls open/visible state of the componenet.
 * 
 * @returns The UploadDialog componenet to be rendered in the app.
 */
function UploadDialog(props) {

    const handleClose = () => {
        props.onClose();
    };

    return(
        <Dialog open={props.open} onClose={handleClose}>
            <DialogTitle>
                Upload Media
            </DialogTitle>
            <Box sx={{margin: '0 5% 0 5%'}}>
                <Typography>
                    Drag and drop into the box, or click the button to browse
                </Typography>
                <UploadBox/>
            </Box>
        </Dialog>
    );
};

export default UploadDialog; 

Jest passes the first two tests of the suite that check if the component renders correctly both open and closed, but the third test that tried to toggle between these states fails.
Here is the test code:

import React from 'react';
import { screen, render } from '@testing-library/react';
import '@testing-library/jest-dom';

import UploadDialog from './UploadDialog';

jest.mock('./UploadBox', () => () => {<div/>});


describe('UploadDialog', () => {
    let handleClose = jest.fn();

    test('renders closed', () => {
        render(<UploadDialog open={false} handleClose={handleClose}/>);
        expect(screen.queryByRole('presentation')).not.toBeInTheDocument();
    });

    test('renders open', () => {
        render(<UploadDialog open={true} handleClose={handleClose}/>);

        // There are two presentation role elements; both should be present
        const expectedElements = screen.getAllByRole('presentation');
        expect(expectedElements[0]).toBeInTheDocument();
        expect(expectedElements[1]).toBeInTheDocument();
    });

    test('toggles open and closed', () => {
        // This piece passes
        const {rerender} = render(
            <UploadDialog open={false} handleClose={handleClose}/>
        );

        expect(screen.queryByRole('presentation')).not.toBeInTheDocument();

        // This also gets through fine
        rerender(<UploadDialog open={true} handleClose={handleClose}/>);

        const expectedElements = screen.getAllByRole('presentation');
        expect(expectedElements[0]).toBeInTheDocument();
        expect(expectedElements[1]).toBeInTheDocument();

        // This is where the problem shows up
        rerender(<UploadDialog open={false} handleClose={handleClose}/>);

        expect(screen.queryAllByRole('presentation').length).toBe(0);
    });
});

The final test fails with the following error:

UploadDialog › toggles open and closed

    expect(received).toBe(expected) // Object.is equality

    Expected: 0
    Received: 2

      50 |         rerender(<UploadDialog open={dialogOpen} handleClose={handleClose}/>);
      51 |
    > 52 |         expect(screen.queryAllByRole('presentation').length).toBe(0);
         |                                                              ^
      53 |     });
      54 | });

When using screen.debug(), I see only the open={true} version of this component. I have checked that this component is behaving correctly in the app, closing and opening when expected (as the first two tests suggest), so this seems to be a problem with React Testing Library. Does rerender only work once in React Testing Library? How do I rerender a second time?

Using Dexie inside WebSQL transaction

I’m having some trouble using Dexie inside a WebSQL transaction. It looks like Dexie closes WebSQL transaction when it’s promise is finished.

The code structure looks something like this:

AccessIndexDBThroughDexie = () => {
    return this.dexieTable.bulkPut(data);
};


Database.read( tx => {
    tx.executeFragment('SQL ...')
    .then((result) => {
        return AccessIndexDBThroughDexie(result);
    })
    .then( () => {
        return tx.executeFragment('SQL ...'); //this execution raises the error on DOM
    })
})

This throws the following error:
DOMException: Failed to execute 'executeSql' on 'SQLTransaction': SQL execution is disallowed.

I tried solving it with Dexie.transaction to see if explicitly creating a transaction for the Dexie operations it would do it, but it didn’t made any difference.
Is there a way to prevent Dexie from interfering with webSQL transactions?

Which programming langauges are backward compatible and which are forward compatible?

Which programming languages are backward compatible and which are forward compatible? I am asking this question because when I found that some languages are deprecating their features in newer version,which existed in older versions and making new code unable to mix up with old code.Why?

I need to know this because I am confused to switch between version of a particular programming language.

Problem in React using DataTable with Bootstrap5

I am using this DataTable, which works correctly, the problem is that when I run it I get this error: “DataTables warning: table id=example – Cannot reinitialise DataTable. For more information about this error, please see https://datatables.net/tn/3“, the solution was to use the following: ‘if ($.fn.DataTable.isDataTable(’#example”)) {
$(“#example”).DataTable().destroy();
}”. But now I have a new problem and I get a very wide and empty column at the end of the table, do you know how to solve it?

import React, { useEffect, useState } from "react";
import $ from "jquery";
import "datatables.net-bs5";

function MyDataTable() {
  const [users] = useState([
    {
      id: 1,
      nombre: "Axel",
      primerApellido: "Rojero",
      segundoApellido: "Flores",
      curp: "HFKJALSITOSPR9AISK",
      rfc: "DJU8ALS9F0SLD",
    },
    {
      id: 2,
      nombre: "Kira",
      primerApellido: "Garfias",
      segundoApellido: "Gonzalez",
      curp: "HFKJALSITOSPR9AISK",
      rfc: "DJU8ALS9F0SLD",
    },
  ]);

  useEffect(() => {
    if ($.fn.DataTable.isDataTable("#example")) {
      $("#example").DataTable().destroy();
    }

    $("#example").DataTable({
      autoWidth: true,
      paging: false,
      searching: true,
      colReorder: true,
      fixedHeader: true,
      responsive: true,
      stateSave: true,
      columns: [
        { title: "Numero de empleado" },
        { title: "Nombre" },
        { title: "Primer apellido" },
        { title: "Segundo apellido" },
        { title: "CURP" },
        { title: "RFC" },
        { title: "Editar" },
        { title: "Borrar" },
      ],
    });
  }, [users]);

  return (
    <div className="container mt-5">
      <h2>Docentes</h2>
      <div className="col mb-3">
        <button type="button" className="btn btn-primary">
          Agregar Usuario
        </button>
      </div>
      <table
        id="example"
        className="table table-striped table-bordered"
        style={{ width: "100%" }}
      >
        <thead>
          <tr>
            <th>Numero de empleado</th>
            <th>Nombre</th>
            <th>Primer apellido</th>
            <th>Segundo apellido</th>
            <th>CURP</th>
            <th>RFC</th>
            <th>Editar</th>
            <th>Borrar</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.id}>
              <td>{user.id}</td>
              <td>{user.nombre}</td>
              <td>{user.primerApellido}</td>
              <td>{user.segundoApellido}</td>
              <td>{user.curp}</td>
              <td>{user.rfc}</td>
              <td>
                <button className="btn btn-warning">Editar</button>
              </td>
              <td>
                <button className="btn btn-danger">Borrar</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default MyDataTable;

Error

DataTable pre-destruction: Used $(“#example”).DataTable().destroy() before each initialization to avoid duplication when re-rendering the table.

Use of useEffect: Table initialization is performed inside useEffect, ensuring that the table is properly destroyed before being re-created.

Disabling of certain settings: Properties such as autoWidth and responsive were disabled to eliminate possible conflicts that could be causing the duplications.

NextJS Hydration Error beacuse of `useMediaQuery` usage

I have a dynamic page like this in nextjs:

/* Imports */

async function getData(id: string) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/homework/${id}`, {
    cache: 'no-cache',
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return (await res.json()) as Homework;
}

export default async function HomeworkPage({
  params,
}: {
  params: { name: string };
}) {
  const data = await getData(params.name);

  return (
    <>
   /* Some client and server components */
    </>
  );
}

This page is rendered using this layout:

'use client';

import { AnnouncementBar } from '@/components/editor/components/announcement-bar';
import { Footer } from '@/components/footer';
import { HeaderApp } from '@/components/header-app';
import { QuickBar } from '@/components/ui/quick-bar';

interface AppLayoutProps {
  children: React.ReactNode;
}

export default function AppLayout({ children }: AppLayoutProps) {
  return (
    <div className='flex min-h-screen flex-col'>
      <AnnouncementBar />
      <HeaderApp />

      <main className='flex flex-1 pt-[calc(var(--announcement-bar-height)+var(--header-height))]'>
        <div className='container px-3 py-6 md:px-6'>{children}</div>
        <QuickBar />
      </main>

      <Footer />
    </div>
  );
}

Where for example in AnnounementBar I have the following logic that uses both lcoalStorage in getUserOrGuest method and useMediaQuery in useIsDesktop:

"use client"

export const AnnouncementBar = () => {
  const user = getUserOrGuest();
  const isDesktop = useIsDesktop();

  return (
    <div
      className={clsx(
        'z-[50] h-[40px] w-full border-y-[1px] border-border/90 scrolled:h-0',
        'flex items-center justify-center text-sm transition-[opacity,height] duration-200',
        'overflow-hidden scrolled:border-none scrolled:leading-[0] scrolled:opacity-0',
        'fixed left-0 top-0 bg-header p-2'
      )}
    >
      <div className='flex items-center gap-1.5'>
        <AlertTriangle className='mr-2' />
        {isDesktop && <span>Platforma jest w wersji</span>}

        <ResponsiveDialog
          trigger={
            <Button
              variant='ghost'
              className='hover:bg-initial m-0 flex gap-1 p-0 text-violet-11 hover:text-violet-12 hover:underline'
            >
              <span className='font-bold'>
                {isDesktop ? 'testowej!' : 'wersja testowa!'}
              </span>
            </Button>
          }
          title='Wersja testowa'
          content={
            <div className='flex flex-col gap-3'>
              <p>
                Ponieważ jesteśmy nowo powstałą platformą, potrzebujemy czasu
                aby przetestować wszystkie funkcjonalności oraz uzupełnić
                platformę o wartościowe treści. Do tego czasu{' '}
                <span className='font-bold text-red-10 underline underline-offset-4'>
                  rejestracja kont ucznia jest wyłączona!
                </span>
              </p>
              <p className='font-bold'>
                Jesteś nauczycielem?{' '}
                <Link className='mw-link' href='/register/teacher'>
                  Dołącz do nas!
                </Link>
              </p>
            </div>
          }
        />
      </div>
      {user && (
        <Link
          className='ml-5 whitespace-nowrap font-bold text-red-10 hover:text-red-11'
          href='/feedback'
        >
          Zgłoś błąd lub sugestię
        </Link>
      )}
    </div>
  );
};

The problem is that for some reason this component is server side rendered and then I have a hydration error because when I reload page, initially the mobile view is rendered and user is null and then it is replaced by the proper view (user is taken from localStorage and isDesktop is false). I don’t really get why is that a case. Any ideas?

loading an svg externally in canvas in fabric js

I want to upload individually all the elements in my svg into to my canvas.

you can see in the console [screenshot of the console(https://i.sstatic.net/Yj3SGXEx.png) that the svg file path is right and the console logs the content properly.

this is my code to upload the svg to my canvas

// URL of the external SVG file
const svgUrl = '../111.svg'; // Replace with your SVG URL

// Load the SVG file
fabric.loadSVGFromURL(svgUrl, (objects, options) => {
    console.log('SVG loaded:', objects);

    // Add objects to the canvas
    if (Array.isArray(objects)) {
        objects.forEach(obj => {
            canvas.add(obj);
        });
    } else {
        canvas.add(objects);
    }

    // Render the canvas
    canvas.renderAll();
}, (error) => {
    console.error('Error loading SVG:', error);
});

algorithmic task Space travel [closed]

I want found solution O (n) algorithm for this problem but unable to do.

After the cataclysm, there are only two ways to travel around the world:

  1. magic ferries that move between neighboring islands (naturally, the ferry can move in both directions), so from the island that is in the i-th place in the cosmic row, you can get to the i-1 and i+1 islands;

  2. portals through which you can teleport between islands regardless of the distance, but only if before the cataclysm these islands formed one continent (interestingly, the continents in this world had numbers, not names).
    It is necessary to find the minimum number of movements from the first island to the last.

    example 1

    11 -86 50 986 7 23 24 25 1846 201 9 19 11 86 2000 201 11 2010 234 156 11 456 488 478 985 6564 45341 3 201 8

answer 4

example 2

1 3 4 5 4 3

answer 2

The solution to the problem using a graph will be rejected because storing the list of nodes and the queue requires a lot of memory.Memory limit in this task 64 mb. Simply put, the solution using a graph is not optimal in terms of memory usage.
My question is there another algorithm to solve this problem. We know that the longest path is equal to the number of elements (islands) in the array.

const readline = require("readline").createInterface(process.stdin, process.stdout)

readline.on("line", line => {
  let arr = line.split(" ").map(Number)
  // console.time()
  const graph = createGraph(arr)
  const last = arr.length - 1
  arr = null
  const nodeState = new Map()
  const startNode = { id: 0, distanceToSource: Number.POSITIVE_INFINITY, visited: false, open: false, heapId: -1 };
  startNode.distanceToSource = 0
  nodeState.set(0, startNode)
  startNode.open = true
  const queue = Queue()
  queue.push(startNode);
  while (queue.length) {
    const parent = queue.pop()
    parent.visited = true
    if (parent.id === last) break
    graph.get(parent.id).forEach(curr => {
      let currNode = nodeState.get(curr);
      if (!currNode) {
        currNode = { id: curr, distanceToSource: Number.POSITIVE_INFINITY, visited: false, open: false, heapId: -1 };
        nodeState.set(curr, currNode);
      }

      if (currNode.visited) return

      if (currNode.open === false) {
        queue.push(currNode);
        currNode.open = true;
      }

      const distance = parent.distanceToSource + 1;
      if (distance >= currNode.distanceToSource) return;

      //currNode.parent = parent.id;
      currNode.distanceToSource = distance;
      // currNode.fScore = distance //+ heuristic(curr, arr.length - 1);
      queue.updateItem(currNode.heapId)
    });
    graph.delete(parent.id)
  }
  // console.timeEnd()
  console.log(nodeState.get(last).distanceToSource)
  readline.close()
}).on("close", () => process.exit(0))

function createGraph(arr) {
  const mapArr = new Map()
  for (let i = 0; i < arr.length; i++) {
    if (!mapArr.has(arr[i])) mapArr.set(arr[i], [i])
    else mapArr.get(arr[i]).push(i)
  }
  const graph = new Map()
  for (let i = 0; i < arr.length; i++) {
    const node = []
    if (i + 1 < arr.length)
      node.push(i + 1)
    if (i - 1 >= 0)
      node.push(i - 1)
    const findKey = mapArr.get(arr[i])
    node.push(...findKey.filter(x => x != i - 1 || x != i + 1))
    graph.set(i, node.filter(x => x != i).sort((a, b) => b - a))
  }
  return graph
}

const heuristic = (from, to) => to - from

function Queue() {
  class PriorityQueue {
    constructor() {
      this.data = []
      this.length = this.data.length;
    }

    compare = (a, b) => { return a.distanceToSource - b.distanceToSource }

    notEmpty() {
      return this.length > 0
    }

    pop() {
      if (this.length === 0) return undefined;

      const top = this.data[0];
      this.length--;

      if (this.length > 0) {
        this.data[0] = this.data[this.length];
        this.data[0].heapId = 0
        this.down(0);
      }
      this.data.pop();

      return top;
    }

    push(item) {
      this.data.push(item);
      item.heapId = this.length
      this.length++;
      this.up(this.length - 1);
    }

    up(pos) {
      const item = this.data[pos];

      while (pos > 0) {
        const parent = (pos - 1) >> 1;
        const current = this.data[parent];
        if (this.compare(item, current) >= 0) break;
        this.data[pos] = current;
        current.heapId = pos
        pos = parent;
      }

      item.heapId = pos
      this.data[pos] = item;
    }

    down(pos) {
      const halfLength = this.length >> 1;
      const item = this.data[pos];

      while (pos < halfLength) {
        let left = (pos << 1) + 1;
        const right = left + 1;
        let best = this.data[left];

        if (right < this.length && this.compare(this.data[right], best) < 0) {
          left = right;
          best = this.data[right];
        }
        if (this.compare(best, item) >= 0) break;

        this.data[pos] = best;
        best.heapId = pos
        pos = left;
      }

      item.heapId = pos
      this.data[pos] = item;
    }
    updateItem(pos) {
      this.down(pos);
      this.up(pos);
    }
  }

  return new PriorityQueue();
}

Unable to nest basic vanilla web component

I have a set of basic web components made out of plain JS. Example:

Account.ts

class Account extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = '<p>My account</p>';
   }
}

customElements.define('account', Account);

Basket.ts

class Basket extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = '<p>My Basket</p>';
   }
}

customElements.define('basket', Basket);

I am trying to create another web component (common) that can be nested in each of the above. For now, lets assume a basic <button> with a click event. I have tried:

CommonButton.ts

class CommonButton extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = '<button onclick="console.log('clicked')">Click Me</button>';
   }
}

customElements.define('common-button', CommonButton);

Account.ts

class Account extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = `
          <p>My Account</p>
          <common-button></common-button>
      `;
   }
}

customElements.define('account', Account);

There are no errors in the browser. I can see in the generated HTML:

<account>
     <p>My Account</p>
     <common-button></common-button>
</account>

However no <button> inside of <common-button>

why browser allow strange javascript: combination

Reading the XSS Filter Evasion Cheat Sheet I have realized as many of the XSS filter evasions are due to particular and strange behaviors that are hidden to common developers.

In particular the following XSS filter evasion techniques have struck me:

  • <SCRIPT/XSS SRC="http://xss.rocks/xss.js"></SCRIPT>
  • <BODY onload!#$%&()*~+-_.,:;?@[/|]^=alert("XSS")>
  • <a href="jav&#x09;ascript:alert('XSS');">Click Me</a>

The point is: why do modern web browsers allow such things? For example, why allowing to have strange characters in the middle on the javascript: directive and not just sticking to it? I’ve never seen a developer writing jav&#x09;ascript: instead of javascript:.

Sap Business Apllication Studio : layout editor error in XML views

I have a Fiori project in Sap BAS. It contains 2 view.

Project1
 -> webapp
   -> view
      -> View1.view.xml
      -> View2.view.xml

Index.html contains:

data-sap-ui-resourceroots='{ "project1": "./" }'

View1 contains an xml view for View2:

<mvc:XMLView viewName="project1.view.View2/>

When I run the app, it displays correctly the view2 in the view1.
But when I starts the Layout editor for View1, it drops the following error:

For scenarios involving fragments and nested views, your project must contain an index.html like or a localIndex.html file containing the data-sap-resourceroots attribute. Currently, your project does not contain such files.

resource project1/view/View2.view.xml could not be loaded from /di/home/user/projects/project1/webapp/./view/View2.view.xml. Check for ‘file not found’ or parse errors. Reason:

Anybody has a clue what did I wrong?
Thanks for the help

I tried to modify the link to view2 several mode, but always error comes.

Two or more time slots in flatpickr

There’s a way to make two or more separate slots in a time picker. Something like:

flatpickr(bookingHour, {
  enableTime: true,
  noCalendar: true,
  dateFormat: "H:i",
  enable: [
    {
      from: "11:30",
      to: "15:30",
    },
    {
      from: "19:30",
      to: "23:45",
    },
  ],
});

Something like enabling range(s) of dates but with time.

TypeError: is not a constructor when importing from my own package

I can’t seem to figure out what’s wrong with the package that I created which I’m now trying to import to my other project.

The main file of the package contains these exports (names changed):

export { Class1 } from './util/translations/class1';
export { Class2 } from './util/translations/class2';

Each file exports a class such as:

export class Class1 {
  private client: Client;

  constructor(config: Config) {
    this.client = new Client(Config);
  }

  async translateText(text: string, targetLanguage: Language): Promise<string> {
    return client.translate(text, targetLanguage)
  }
}

My package.json has these settings:

  "main": "dist/Localisation.js",
  "types": "dist/Localisation.d.ts",
  "files": [
    "dist/**/*"
  ],

My tsconfig.json:

"compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "target": "es2017",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "types": ["node", "jest"],
    "typeRoots": ["./node_modules/@types", "./types"],
    "baseUrl": "."
},
  "include": ["src/**/*.ts"],
  "exclude": [
    "node_modules",
  ]

I run tsc to compile the project and get the dist folder. The main file in dist looks like this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Language = exports.Class1 = exports.Class2 = void 0;
var class1_1 = require("./util/translations/class1");
Object.defineProperty(exports, "Class1", { enumerable: true, get: function () { return class1_1.Class1; } });
var class2_1 = require("./util/translations/class2");
Object.defineProperty(exports, "Class2", { enumerable: true, get: function () { return class2_1.Class2; } });
var languages_1 = require("./util/languages");
Object.defineProperty(exports, "Language", { enumerable: true, get: function () { return languages_1.Language; } });
//# sourceMappingURL=Localisation.js.map

I then run npm publish to publish my package with a bumped version. I pull that version in my other project and try to import Class1 and Class2.

import { Class1, Class2 } from "my-package";

But when I try to construct an instance of Class1, I’m getting Class1 is not a constructor. When I console log the imported Class1, I’m getting undefined as if it doesn’t exist at all on the package or as if the export didn’t work.

I’ve tried so many things, including:

  • changing exports in the package to export default
  • moving all my classes to the main file of the project instead of exporting them in the main file
  • using tsup instead of tsc

A very strange thing about is that I’m also exporting an enum in the same way in that same main file (from another folder within the package) and that enum is actually available and not null, the only thing that gets exported correctly.

I’m honestly not sure what I can do or try in this case.