Are there no limits to Javascript/Typescript file extensions? [closed]

I see people using extensions like .d.ts, .schema.ts, .route.ts, routes.ts and basically anything and everything, so I was wondering if there is no limit to the extensions you can give to your files in typescript/javascript (I’ve seen people do this with javascript too). So someone kindly explain what are these extensions and how to use them.

Thank you.

Why Sequelize migration create my table with only 1 foreing key instead of 2?

Im trying to make a intermediate table between 2 models, called User and Reminder.
The fact is everytime i try to migrate or create the table UserReminders I dont get 2 foreing keys, userId and reminderId, instead I only get ONE foreing key, which is reminderId.

This is what appears on my table on heidiSQL

I created a model on my backend called UserReminder and the migration of it for my database on HeidiSQL.

MODEL:

import { Model } from 'sequelize'

const loadModel = (sequelize, DataTypes) => {
  class UserReminder extends Model {
    static associate (models) {
      // Un UserReminder pertenece a un usuario
      UserReminder.belongsTo(models.User, { foreignKey: 'userId', onDelete: 'CASCADE' })
      // Un UserReminder pertenece a un recordatorio
      UserReminder.belongsTo(models.Reminder, { foreignKey: 'reminderId', onDelete: 'CASCADE' })
    }
  }

  UserReminder.init({
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Users',
        key: 'id'
      },
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE'
    },
    reminderId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Reminders',
        key: 'id'
      },
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE'
    },
    createdAt: {
      allowNull: false,
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW
    },
    updatedAt: {
      allowNull: false,
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW
    }
  }, {
    sequelize,
    modelName: 'UserReminder',
    tableName: 'UserReminders',
    timestamps: true,
    indexes: [
      {
        unique: true,
        fields: ['userId', 'reminderId']
      }
    ]
  })

  return UserReminder
}

export default loadModel

MIGRATION:

'use strict'
/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
    await queryInterface.createTable('UserReminders', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      userId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'Users',
          key: 'id'
        },
        onDelete: 'CASCADE'
      },
      reminderId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'Reminders',
          key: 'id'
        },
        onDelete: 'CASCADE'
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.fn('now')
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.fn('now')
      }
    })

    await queryInterface.addConstraint('UserReminders', {
      fields: ['userId', 'reminderId'],
      type: 'unique',
      name: 'unique_user_reminder'
    })
  },

  async down (queryInterface, Sequelize) {
    await queryInterface.dropTable('UserReminders')
  }
}

I was expecting to have 1 primary key called id, 2 foreing keys userId and reminderId, and one unique key compound (userId, reminderId). But i got the things I said but with only ONE foreing key (reminderId) instead of 2.

Having trouble using assistants with openai api with firebase cloud functions. I am using this npm package https://www.npmjs.com/package/openai

I’ve looked through the documentation. Can someone point me in the right direction? I’m simply trying to learn to create a assistant with a firebase cloud function and use an assistant. Just those two functions. couldn’t find it anywhere

I’m able to use the normal chatgpt api but not the one with the assistants. I believe I need an assistant id and then later on a thread id to mantain the conversation. Any help is appreciated. Thanks.

TypeError: Response body object should not be disturbed or locked when using Next.js with Express

I’m encountering an error while using Next.js with a custom Express server. The error message is:

TypeError: Response body object should not be disturbed or locked

This occurs during API requests when I send a body with a POST request. The requests without a body (GET, even POST without sending a body, etc.) work fine.

I’m using a custom server with Express and have added middleware to allow Next.js to handle routing. The pages are served correctly, but the issue arises with the API route handler.

Here is the relevant part of my server setup:

import express from 'express';
import dotenv from 'dotenv';
import next from 'next';
import path from 'path';

dotenv.config({
    path: path.resolve(__dirname, '../.env'),
});

const PORT = Number(process.env.PORT) || 3000;

const app = express();
const nextApp = next({
    dev: process.env.NODE_ENV !== 'production',
    port: PORT,
    hostname: 'http://localhost',
});

const nextHandler = nextApp.getRequestHandler();

async function start() {
    await nextApp.prepare();
    app.use(express.json()); // Ensure the body parser is included
    app.use((req, res) => nextHandler(req, res));

    app.listen(PORT, () => {
        console.log(`Server started, and running at http://localhost:${PORT}`);
    });
}

start();

What I’ve Tried

  • Adding express.json() middleware: I included app.use(express.json()); to parse incoming JSON requests.
  • Ensuring proper order of middleware: I’ve made sure that the body parser is set up before the Next.js handler.
  • Checking for conflicting middlewares: I verified that no other middleware is interfering with the request handling.

Question

What could be causing this TypeError when sending a body with POST requests? How can I resolve this issue to ensure that my API routes work correctly with body data?

My version of next is 14.2.5 and my version of express is 4.18.2

Thank you for your assistance!

How do I get descriptor for JavaScript class constructor function?

Is it possible for me to get the descriptor for the actual constructor method of a JS class? I am writing my own little wrapper around Express to try and procedurally generate routes and stuff (and I am sure there are plenty of other libraries to do this, but it’s a learning experience).

If I iterate through the function descriptors for a class prototype, I can convert the ‘value’ property to a string that represents a single method. If I call getString() on the descriptor for ‘constructor’ I get the entire class. I ONLY want the body of the constructor. I could add more parsing logic, but there has to be a way to do this.

Here is a simple controller:

const
    BaseController = require('../src/baseController');

/**
 * Handle requests for the home page
 */
class HomeController extends BaseController {
    /**
     * @param settings Controller settings
     * @param vault Injected vault client
     */
    constructor(settings, vault) {
        super(settings);
        this.vault = vault;
    }

    /**
     * Serve the landing page
     * @returns 
     */
    async get() {
        await this.renderAsync({ pageTitle: 'Pechanga Demo' });
    }
}

module.exports = HomeController;

Here is what currently comes back for ‘get’:

Object.getOwnPropertyDescriptor(controllerType.prototype, 'get').value.toString()

async get() {
   await this.renderAsync('index', { pageTitle: 'Pechanga Demo' });
}

However, getting the descriptor for ‘constructor’ returns the entire class body:

Object.getOwnPropertyDescriptor(controllerType.prototype, 'constructor').value.toString()

I really want is just:

    constructor(settings, vault) {
        super(settings);
        this.vault = vault;
    }

Is this possible without parsing the entire class body?

How in iOS keep playing video after exiting fullscreen and put away additional controls?

On my wordpress site there are a couple of videos that could play in fullscreen mode, but only in iPhones I have an issue with video: it is getting paused when then leaving the fullscreen mode to normal mode and shows both the iOS video player controls and the presto player controls which looks very confusing.
Besides, in iOS 17.2 there is a dark screen in fullscreen mode instead of full length video.

enter image description here

Here is an example of code:

var lazyVideos = [].slice.call(document.querySelectorAll("video.lazy"));

if ("IntersectionObserver" in window) {
  var lazyVideoObserver = new IntersectionObserver(function(entries, observer) {
    entries.forEach(function(entry) {
      if (entry.isIntersecting) {
        var video = entry.target;
        var source = video.querySelector("source");

        // Load and play the video from data-src
        if (source && source.dataset.src) {
          source.src = source.dataset.src;
          video.load();
          video.play();
        }

        video.classList.remove("lazy");
        lazyVideoObserver.unobserve(video);
      }
    });
  });

  lazyVideos.forEach(function(lazyVideo) {
    lazyVideoObserver.observe(lazyVideo);
  });
}

function isIOS() {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}
// Add event listener to play button
document.querySelectorAll(".playbutton").forEach(function(button) {
  button.addEventListener("click", function() {
    var container = this.closest(".video-container");
    var fa = container.querySelector(".fa");
    var video = container.querySelector("video");
    var source = video.querySelector("source");

    if (video && source) {
      // Pause the current video
      video.pause();

      // Load the full video
      if (source.dataset.fullsrc) {
        source.src = source.dataset.fullsrc;
      }
      video.load();
      video.controls = true;
      video.loop = false;

      // Play the full video in fullscreen mode
      video.addEventListener('loadeddata', function() {
        if (video.requestFullscreen) {
          video.requestFullscreen();
        } else if (video.mozRequestFullScreen) { // Firefox
          video.mozRequestFullScreen();
        } else if (video.webkitRequestFullscreen) { // Chrome, Safari and Opera
          video.webkitRequestFullscreen();
        } else if (video.msRequestFullscreen) { // IE/Edge
          video.msRequestFullscreen();
        } else if (isIOS() && video.webkitEnterFullscreen) { // iOS Safari
          video.webkitEnterFullscreen();
        }

        video.play();
      }, {
        once: true
      });

      // Exit fullscreen and remove controls when the video ends
      video.addEventListener('ended', function() {
        if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.mozCancelFullScreen) { // Firefox
            document.mozCancelFullScreen();
          } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
            document.webkitExitFullscreen();
          } else if (document.msExitFullscreen) { // IE/Edge
            document.msExitFullscreen();
          }
        }
        video.controls = false;
      }, {
        once: true
      });

      // Handle manual exit from fullscreen mode
      var handleFullscreenChange = function() {
        if (!(document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement)) {

          video.controls = false;

          if (fa.classList.contains("fa-play") && video.play) {
            fa.classList.remove("fa-play");
            fa.classList.add("fa-pause");
          }

          if (isIOS()) {
            video.controls = false;
            video.play();
          }

          document.removeEventListener('fullscreenchange', handleFullscreenChange);
          document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
          document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
          document.removeEventListener('msfullscreenchange', handleFullscreenChange);
        }
      };
    }
  });
});
<div class="video-wrapper section_video" id="animationvideo">
  <div class="video-container">
    <video class="img-fluid lazy animation-video" width="600" height="400" autoplay loop muted playsinline poster="https://www.w3schools.com/w3css/img_forest.jpg">
       <source data-src="https://www.w3schools.com/html/mov_bbb.mp4" data-fullsrc="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
    </video>
    <button class="playbutton" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="expand-tooltip play-tooltip" data-bs-trigger="hover" title="Pause animation" aria-label="Play or pause this animation by clicking this link">Play full video<i class="fa fa-play" aria-hidden="true"></i></button>
  </div>
</div>

I tried to switch functionality from the wordpress core player to the native player for fullscreen the method of which is described on the forum, but it didn’t help me.

add_action(
    'wp_footer',
    function () { ?>
    <script>
        jQuery(function() {
            if (!wp || !wp.hooks) return;
            wp.hooks.addFilter('presto.playerSettings', 'ios-native-fullscreen', function(settings) {
                settings.fullscreen = { enabled: true, fallback: true, iosNative: true, container: null };
                return settings;
            });
        });
    </script>
        <?php
    }
);

Button border highlight effect [duplicate]

I want to make a button that has this highlight effect when the user hovers over it that works with rounded corners. (Effect is the second button)

https://codepen.io/sarath-ar/pen/dMKxxM

.btn-2::before,
.btn-2::after {
  transition-delay: 0s;
}

.btn-2 span::before,
.btn-2 span::after {
  transition-delay: 0.2s;
}

.btn-2::before {
  right: 0;
  top: 0;
}

.btn-2::after {
  left: 0;
  bottom: 0;
}

.btn-2 span::before {
  left: 0;
  top: 0;
}

.btn-2 span::after {
  right: 0;
  bottom: 0;
}

.btn-2:hover::before,
.btn-2:hover::after {
  transition-delay: 0.2s;
}

.btn-2:hover span::before,
.btn-2:hover span::after {
  transition-delay: 0s;
}
<button class="btn-2"><span>Hover Me</span></button>

I have been unable to successfully make the effect work for a curved button

How to use proxy that has authentication in selenium-webdriver?

I need help on how to use proxy that has authentication in selenium-webdriver in javascript. If the proxy only use host:port, the webdriver works fine. But if i use proxy like user:pass@host:port, the webdriver cant reach the url.

const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

(async function example() {
    const proxyUrl = `http://user:pass@host:port`;

    const opts = new chrome.Options()
        .addArguments(
            `--proxy-server=${proxyUrl}`,
        );

    const driver = new webdriver.Builder()
        .forBrowser('chrome')
        .setChromeOptions(opts)
        .build();

    try {
        await driver.get("https://ipinfo.io/json");

        const pageSource = await driver.getPageSource();
        
        console.log(pageSource);
    } finally {
        await driver.quit();
    }
}());

And this is what i got when i use proxy that has auth:

<script jstcache="0">
  var loadTimeDataRaw = {
    "details": "Details",
    "errorCode": "ERR_NO_SUPPORTED_PROXIES",
    "fontfamily": "'Segoe UI', Tahoma, sans-serif",
    "fontfamilyMd": "'Segoe UI', Tahoma, sans-serif",
    "fontsize": "75%",
    "heading": {
      "hostName": "ipinfo.io",
      "msg": "This site can’t be reached"
    },
    "hideDetails": "Hide details",
    "iconClass": "icon-generic",
    "language": "en",
    "suggestionsDetails": [],
    "suggestionsSummaryList": [],
    "summary": {
      "failedUrl": "https://ipinfo.io/json",
      "hostName": "ipinfo.io",
      "msg": "The webpage at u003Cstrong jscontent="failedUrl">u003C/strong> might be temporarily down or it may have moved permanently to a new web address."
    },
    "textdirection": "ltr",
    "title": "ipinfo.io"
  };
</script>undefined</body>undefined</html>

Nodejs application is not rendering the HTML on my vercel site

I have been facing some issue with my application that I hosted on the Vercel, but the problem i am facing is that it is only rendering response as JSON rather than the full index.html.

This is in my localhost

This is on my vercel websitehttps://task-manager-five-sepia.vercel.app/

I am not sure what is i am missing in my vercel website repo.

Expectation was that it shows me the application just like what i am able to use it in my localhost.
NOTE : Deployment related things are sorted in vercel, every change i make in my repo

File Download – Open file in a new Tab

I am using TelerikUpload control for file Upload. I am able to upload and download file without any issue. Currently for download when I click on download its downloading the file to Download folder. Instead of downloading, I want the file to be opened in a new browser tab without downloading. Any help on how this can be achieved. Please see my below code.

//Razor file
<script type="text/javascript">
    function downloadAttachment(filename, content, mimeType) {
        var blob = new Blob([content], { type: mimeType });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);        
        link.download = filename;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
</script>
<TelerikButton  @onclick="() => AttachmentDownload(item)">Download</TelerikButton>


//Razor.cs file
 private async Task AttachmentDownload(Attachment attachment)
 {
     var extension = Path.GetExtension(attachment.fileName);
     var mimeType = MimeTypeHelper.GetMimeType(extension);
     byte[] ByteArray = FileStorage.ReadFile(attachment.Path);

     if (ByteArray != null)
     {
         await JSRuntime.InvokeVoidAsync("downloadAttachment", attachment.fileName, ByteArray, mimeType);
     }           
 }
 
 public static string GetMimeType(string extension)
{
    switch (extension)
    {
        case ".pdf":
            return "application/pdf";
        case ".csv":
            return "text/csv";
        case ".txt":
            return "text/plain";
        default:
            return "application/octet-stream";
    }
}

how to remove an attribute of an element using mutationObserver and mutationrecord?

I’ve been using this code below to remove attributes added by a 3rd party library from my webapp on runtime.

document.addEventListener('DOMNodeInserted', () => {
  const elements = document.querySelectorAll('[aria-owns]');
  elements.forEach(element => {
    element.removeAttribute('aria-owns')
  })
})

However recently, we’ve been getting this error in the console:

[Deprecation] Listener added for a ‘DOMNodeInserted’ mutation event.
Support for this event type has been removed, and this event will no
longer be fired. See https://chromestatus.com/feature/5083947249172480
for more information.

The summary is that DOMNodeInserted shouldn’t be used anymore for performance reasons, and more importantly bc it will stop working in the near future. It links to an article that mentions that using MutationObserver is the viable option.

However, MutationObserver doesn’t expose Elements, just nodes.

This is what I tried:

const observer= new MutationObserver(mutationList =>{
  mutationList.forEach(mutationRecord => {
    const elements= document.querySelectorAll('[aria-owns]');
    elements.forEach(element => 
      element.removeAttribute('aria-owns')
    )
  })
});
observer.observe(document, {
  childList: true, 
  subtree: true, 
  attributeFilter: ['aria-owns']
};

but if I understand correctly how MutationObserver works, then it feels like an overkill to get all the elements in the document with document.querySelectorAll('[aria-owns]') then iterate over them one by one to remove the attribute, if mutationRecod already yields a collection of the nodes that have just mutated and contain the attribute I am looking for.

is there a way to access the element from the nodes yielded by the MutationObserver?
or what is the correct way to edit the attributes of the nodes with a MutationObserver?

Flutter web app – FCM not working after reload page

I have a Flutter Web application. In it, I use push notifications. The start screen is the login screen. I have two scenarios:

  1. First launch of the application:
    When the user clicks “login”, I request permission to receive push notifications – a dialog appears, and I register handlers for notifications.

    NotificationSettings result = await FirebaseMessaging.instance.requestPermission();
    

Currently, everything works fine.

  1. Reloading the page in the browser:
    However, when I reload the page in the browser, it doesn’t work.
    Although the login page opens after reloading, and I click “login”.
    The same code as in “scenario 1” is executed when clicking. The only difference is that the “permission dialog” does not appear, but that makes sense since I have already granted permission. However, in this case, push notifications do not work.

what could be the reason? how to fix it?

Migrating from ckeditor 4 to ckeditor 5 does not produces HTML and Plain Text as expected plus causing emailing problems

Because ckeditor 4 is showing a EOL warning, I’m now trying to migrate to ckeditor 5. However, I ‘m having multiple problems with ckeditor 5. One problem is with on change and getting plain text from the HTML textbox. Other problems are with view source layout is narrow and changes how the HTML code looks from what I was expecting. Also, the saved HTML and Plain text is causing mail delivery error: ” message has lines too long for transport”

I had this JavaScript code in ckeditor 4:

'on: {
    change: function( evt ) {
     // Do somethign here
    ckText = CKEDITOR.instances.htmltext.getData();
var div = document.createElement("div");
div.innerHTML = ckText;
var cleanText = div.textContent || div.innerText || "";
document.getElementById("plaintext").value = cleanText;
    }
} '

It worked great!

but with ckeditor 5 with this code:

'  editor.model.document.on('change:data', () => {                    
  // Do somethign here   
 var div = document.createElement("div");
 div.innerHTML = editor.getData();
var cleanText = div.textContent || div.innerText || "";
document.getElementById("plaintext").value = cleanText;
          }
      }


ckeditor 5 removes all of the spacing between the paragraphs. Making it one continuous block.

The other problem is when I click on show source, I’m expecting to see HTML code similar to what I see when I’m coding a website, but what I’m seeing is new lines for every p and /p tag. It also changes the width for the textbox.

Plus, emails are being kicked backed as not deliverable because of error. I was testing the same email body that was originally created in ckeditor 4 that had no problem being delivered.

One Page Website Issues With Backwards and Forward Browser Action

I am working on a one page website engine where I load pages into a single DIV. The link is in a DIV such as the one below.

<div id="nav" title="Homepage" data-target="practice-page-1.php" data-value="?url=homepage">Homepage</div>

data-target = is a php file

data-value = a URL that I add at the time the php file is loaded into the content DIV

I am trying to load the correct page into the content DIV when the user uses the back or forward button in the browser. The actual website address never changes, but I append a unique URL to it for different functionalities. I can capture the full URL using the below. The back and forward buttons do move through URLs, but the usual methods to capture these movements don’t work. I need the content in the DIV to move along with browser backward and forward action.

//DETECT ANY NAVIGATION CHANGE AND LOAD PAGE FOR FORWARD AND BACKWARD CHANGES  
        window.navigation.addEventListener("navigate", (event) => {
            var changedURL = event.destination.url;
            console.log(changedURL);
})

changedURL shows the hole URL (example: practice.php?url=page3). I just want the part starting with the question mark and after (my added URL), which is the data-element “value”. I need to cut the value out of the address and then find the corresponding target (practice-page-3.php).

Then I can load that target file into the content DIV just fine.

React App throwing error – Something went wrong

I want to add Options value in the reportFields List dynamically using the categoryOptions state management which get the values from the getAllCategories function. I’m going somewhere wrong but don’t know where.

    import { useState, useEffect } from 'react';
    
    const getAllCategories = () => {
      let url = `/category/list/active`;
      return http.get(url)
        .then(response => {
          const data = response.data;
          if (data.ok) {
            return data.data;
          } else {
            return [];
          }
        })
        .catch(error => {
          console.error('Error:', error);
          return [];
        });
    };
    
    interface Category {
      id: string;
      name: string;
    }
    
    const [categoryOptions, setCategoryOptions] = useState([]);
    
    useEffect(() => {
      async function getCategoryOptions() {
        const categories = await getAllCategories();
        setCategoryOptions(
          categories.map((category: Category) => ({
            value: category.name,
            text: category.name,
          }))
        );
      }
      getCategoryOptions();
    }, []);
    
    
    export const reportFields = [
      {
        "headerName": "Category",
        "field": "category_id",
        "disabled":false,
        "default":true,
        "prefix": "",
        "suffix": "",
        "dbField": "final.category_name",
        "type": "string",
        "options": categoryOptions
      }
    ]