HighCharts does not render (/create elements) – how to debug / check for failure

We’re currently changing some pages to a new kind of layout, but still using the same layout page we’ve always used, just a different kind of topmenu style is used (added using a collection to the view – if it exist, show that topmenu – if it doesn’t show the old)

The chart has always worked before – it’s not new. In other pages (also with the new “topmenu”) other highcharts still work, but in one particular page the chart does not draw or to be more specific, it does not create the highcharts elements within the container – also: There is no error message, no console log, but also no chart – just nothing.

If I use the script to create the chart and paste it into a JSFiddle from a Highchart demo is works (as it did) – but not on this page.

And I have no clue as where to start to debug this particular page. If I git-revert to the old page (same Razor component to create the chart btw) all works as intended. Change to the new; nothing : the only thing changed is a partial with a collection that’s added to the view – and in other views there is no problem whatsoever.

What configuration should be used to obfuscate Angular 18 project with javascript-obfuscator?

What configuration should be used to obfuscate Angular 18 project with javascript-obfuscator ?

I am using package.json

{
  "name": "angular.dev",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "NG_BUILD_PARALLEL_TS=0 ng serve",
    "build": "ng build --configuration production",
    "watch": "ng build --watch --configuration development"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^18.0.0",
    "@angular/cdk": "^18.0.0",
    "@angular/common": "^18.0.0",
    "@angular/compiler": "^18.0.0",
    "@angular/core": "^18.0.0",
    "@angular/forms": "^18.0.0",
    "@angular/material": "^18.0.0",
    "@angular/platform-browser": "^18.0.0",
    "@aws-amplify/ui-angular": "^5.0.19",
    "aws-amplify": "^6.5.3",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.0"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^18.0.0",
    "@angular/build": "^18.0.1",
    "@angular/cli": "^18.0.0",
    "@angular/compiler-cli": "^18.0.0",
    "javascript-obfuscator": "^4.1.1",
    "typescript": "~5.5.0",
    "webpack-cli": "^5.1.4"
  }
}

with Angular 18, javascript-obfuscator version 4.1.1 and @angular-builders/custom-webpack version 18.0.0

My angular.json file is

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "first-app": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "inlineTemplate": true,
          "inlineStyle": true,
          "style": "scss",
          "skipTests": true
        },
        "@schematics/angular:class": {
          "skipTests": true
        },
        "@schematics/angular:directive": {
          "skipTests": true
        },
        "@schematics/angular:guard": {
          "skipTests": true
        },
        "@schematics/angular:interceptor": {
          "skipTests": true
        },
        "@schematics/angular:pipe": {
          "skipTests": true
        },
        "@schematics/angular:resolver": {
          "skipTests": true
        },
        "@schematics/angular:service": {
          "skipTests": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            },
            "main": "src/main.ts",
            "outputPath": "dist/first-app",
            "index": "src/index.html",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "assets": [
              {
                "glob": "**/*",
                "input": "public"
              }
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kB",
                  "maximumError": "1MB"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kB",
                  "maximumError": "4kB"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "optimization": false,
              "extractLicenses": false,
              "sourceMap": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular/build:dev-server",
          "configurations": {
            "production": {
              "buildTarget": "first-app:build:production"
            },
            "development": {
              "buildTarget": "first-app:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular/build:extract-i18n"
        }
      }
    }
  },
  "cli": {
    "analytics": false
  }
}

and webpack.config.js is

const JavaScriptObfuscator = require('javascript-obfuscator');

module.exports = {
    mode: 'development',
    plugins: [
  new JavaScriptObfuscator(
      {
       rotateStringArray: true,
       stringArray: true,
       stringArrayEncoding: ['rc4'],
       stringArrayThreshold: 0.75,
      },
      ['vendor.js']
  ),
 ],
};

when I am running this project with npm run build i am getting the error :

[error] ValidationError: Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.plugins[12] misses the property 'apply'. Should be:
   function
   -> The run point of the plugin, required method.
    at validate (D:codetempplayground_0-hello-worldnode_moduleswebpacknode_modulesschema-utilsdistvalidate.js:191:11)
    at validateSchema (D:codetempplayground_0-hello-worldnode_moduleswebpacklibvalidateSchema.js:78:2)
    at create (D:codetempplayground_0-hello-worldnode_moduleswebpacklibwebpack.js:130:24)
    at webpack (D:codetempplayground_0-hello-worldnode_moduleswebpacklibwebpack.js:182:32)
    at Object.f [as webpackFactory] (D:codetempplayground_0-hello-worldnode_moduleswebpacklibindex.js:73:50)
    at createWebpack (D:codetempplayground_0-hello-worldnode_modules@angular-devkitbuild-webpacksrcbuilderswebpackindex.js:28:36)
    at runWebpack (D:codetempplayground_0-hello-worldnode_modules@angular-devkitbuild-webpacksrcbuilderswebpackindex.js:40:12)
    at D:codetempplayground_0-hello-worldnode_modules@angular-builderscustom-webpacknode_modules@angular-devkitbuild-angularsrcbuildersbrowserindex.js:116:47
    at D:codetempplayground_0-hello-worldnode_modulesrxjssrcinternaloperatorsswitchMap.ts:109:21
    at OperatorSubscriber._this._next (D:codetempplayground_0-hello-worldnode_modulesrxjssrcinternaloperatorsOperatorSubscriber.ts:70:13)

enter image description here

Can anyone suggest which package.json, angular.json and webpack.config.js configuration should be used to obfuscate Angular 18 project using javascript-obfuscator?
Are there any other options to obfuscate Angular 18 project code?

How to structure a long running js process?

I’d like to run a complex calculation on browser using JavaScript. So far my efforts just hang the browser, whereas I would like to provide progress updates to reassure user that things are working as expected. Any pointers or references on how to tackle this would be gratefully received.

Why is my loop not exiting immediately upon success (javascript)

This is a beginner project; for this aspect I’m creating a simple password function that allows the user 3 attempts before exiting the program. The loop should end on ANY loop increment where the password is correct. However the loop works on first attempt if true but if the first attempt is wrong and the second attempt is correct the loop still continues and repeats the password prompt. I apologize if my explanation isn’t as detailed as required as I’m new here

Example:

const prompt = require("prompt-sync")();

const userpasswordkey = "Snow";

function password() {
  let pwcount = 0;

  while (pwcount < 2) {
    let loginpassword = prompt("Enter Database password: ");

    if (loginpassword === userpasswordkey) {
      console.log("Login Complete");
      return true;
      // Exit the function early if the login succeeds
    } else {
      console.log("Try Again");
      pwcount++;
    }
  }
  console.log("password limit reached, Program Terminated.");
  return false; //Return false if password attempts fail
}

password();
if (password()) {
  //checks if password returned true
  //  console.clear();
  console.log("Correct logic")
}

I have also tried using breaks and the loop still carries on

Type-safe function to merge path segments based on an array of keys

The following Paths type represents a number of url paths broken up by path segment.

type PathSegment = {
    path: string;
    children: Paths;
}

type Paths = Record<string, PathSegment | string>;

The following is an example object matching this type:

const paths: Paths = {
    home: "/",
    profile: "/profile",
    settings: {
        path: "/settings",
        children: {
            general: "/general",
            account: "/account",
        }
    }
}

Is it possible to create a function that merges path segments together in a type-safe way by providing the keys of the paths that should be merged? For example, given the paths object above, I could do something like:

const accountSettingsPath = mergePathSegments(paths, ["settings", "account"]);
console.log(accountSettingsPath); // outputs "/settings/account"

The keys passed in via the array should be known at compile-time so that a typo can’t be made. And the array can’t be bigger than the number of keys that are available. Is something like this possible?

How to use math.pow when the base is a negative number and the exponent is a decimal?

Math.pow(-3, 2,6)would give me NaN

Would it be correct to turn it in the following:

if exponent number before the decimal point is even (turn negative into positive)): Math.pow(3, 2,6)

if exponent number before the decimal point is odd (turn negative into positive first and make result negative again after calculation):

Math.pow(3, 2,6)
= 157.49069663608591
// make negative: -157.49069663608591

Is this way plain wrong or is there another way without rounding up or down the exponent?

Dynamically Updating A Card as I Receive information

I’m trying to update a card element in ASPX and ASPX.cs which returns the values that a user has entered and some description of them before sending it off as an email to whom it concerns. So far, even though the modal is triggered, the card is not visible and so also the updated values.

        <div class="row">
            <div class="col" data-bs-toggle="modal" data-bs-target="#addLendAFriend"><asp:Calendar ID="AvailabiltyCalendar" OnSelectionChanged="Availability_Calendar_SelectionChanged" runat="Server"/></div>
            <div class="col">
                <asp:Repeater ID="personalLibrary" OnItemDataBound="personalLibrary_ItemDataBound" runat="Server">
                    <ItemTemplate>
                        <div class="card">
                            <div class="card-body">
                                <p>Book Check-In<%# Eval("dateCheck") %><br />
                                    Genre<%# Eval("sqlGenre") %><br />
                                    Pages<%# Eval("sqlPages") %><br />
                                    Author <%# Eval ("sqlAuthor") %>
                                    </p>
                                <small><i>Press the submit button if the information entered is correct.</i></small>
                            </div>
                        </div>
                    </ItemTemplate>
                </asp:Repeater>
            </div>
        </div>
    </div>
</div>

       <div class="modal align-items-center" role="document" id="addLendAFriend" tabindex="-1" runat="Server" clientidmode="static">
           <div class="container d-flex justify-content-center">
               <div class="modal-dialog">
                   <div class="modal-content">
                       <div class="modal-header">
                           Lend A Friend
                       </div>

                       <div class="modal-body">
                           <div class="row mt-2 mb-2">
                               <div class="col">
                                   <label for="cdueDate" class="form-label">CheckIn</label>
                                   <asp:TextBox class="form-control" id="cdueDate" readonly />
                               </div>
                           </div>

                           <div class="row mb-2 g-6">
                               <div class="col">
                                   <label class="form-label">Select Genre</label>
                                   <asp:DropDownList
                                       AutoPostBack="true"
                                       ClientIDMode="Static"
                                       CssClass="form-select"
                                       required=""
                                       DataSourceID="sSQLGenre"
                                       DataTextField="sqlGenre"
                                       DataValueField="sqlGenre"
                                       ID="ldfGenre"
                                       OnChange="return false;"
                                       runat="Server"></asp:DropDownList>
                               </div>
                           </div>

                           <div class="row g-6">
                               <div class="col">
                                   <label class="form-label">Select Author</label>
                                   <asp:DropDownList
                                       AutoPostBack="true"
                                       ClientIDMode="Static"
                                       CssClass="form-select"
                                       required=""
                                       ID="ldfAuthor"
                                       OnChange="return false;"
                                       DataSourceID="sSQLAuthor"
                                       DataTextField="sqlAuthor"
                                       DataValueField="sqlAuthor"
                                       runat="Server"></asp:DropDownList>
                               </div>
                           </div>

                           <div class="row g-6">
                               <div class="col">
                                   <label class="form-label">Select Pages</label>
                                   <asp:DropDownList
                                       AutoPostBack="true"
                                       ClientIDMode="Static"
                                       CssClass="form-select"
                                       required=""
                                       ID="ldfPages"
                                       OnChange="return false;"
                                       runat="Server">
                                           <asp:ListItem Value="ldfsmall" Text="Between 50-100"></asp:ListItem>
                                           <asp:ListItem Value="ldfmedium" Text="Between 100-200"></asp:ListItem>
                                           <asp:ListItem Value="ldfcrazy" Text="Between 250-500"></asp:ListItem>
                                   </asp:DropDownList>
                               </div>
                           </div>
                       </div>

                       <div class="modal-footer">
                           <div class="row justify-content-end">
                               <div class="col-auto">
                                   <asp:Button 
                                       CssClass="btn btn-secondary"
                                       ID="sCancelCheckOutForm"
                                       OnClick="sCancelCheckOutForm_Click"
                                       Text="Cancel"
                                       runat="Server"/>
                               </div>
                               <div class="col-auto">
                                   <asp:Button 
                                       CssClass="btn btn-primary"
                                       ID="sSubmitldfForm"
                                       OnClick="sSubmitldfForm_Click"
                                       Text="Submit"
                                       runat="Server"/>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>
           </div>
       </div>

       <%--Form Content --%>
       <div class="row justify-content-end">
           <div class="col-auto pt-4 mb-5">
               <asp:Button CssClass="btn btn-success" ID="Submitldf" OnClick="Submitldf_Click" runat="Server" Text="Lorem Ipsum or Latin"></asp:Button>
           </div>
       </div>

<script>
    document.getElementById('sSubmitldfForm').addEventListener('click', function () {
        // Access the calendar value directly
        var selectedDate = document.getElementById('<%= AvailabiltyCalendar.ClientID %>').value;

        // Update the TextBox with the selected date
        document.getElementById('cdueDate').value = selectedDate;
        document.getElementById('display_info').innerHTML = '<h3>Lend A Friend</h3>' + '<p>Thank you for using Lend A Friend. The orange cat has your title knocked over. Don't forget to pick it up</p><br />' +
            'Date: ' +  + '<br/>' +
            'Genre: ' + document.getElementById('ldfGenre').value + '<br/>' +
            'Author: ' + document.getElementById('ldfAuthor').value + '<br/>' +
            'Pages: ' + document.getElementById('ldfPages').value;

        // Optionally hide the modal after submitting
        var myModalOT = new bootstrap.Modal(document.getElementById('add'));
        myModalOT.hide();
    });
</script>

I’ve tried to modify the JS and ASPX which have led to the card no longer been seen. I added the repeater to bind the data from the sql to see if that would work instead and display but nothing as well. Searching Stack Overflow hasn’t yielded any results which solve my problem. If anyone can help me point out where I messed up or even provide a solution, that would be amazing. I can also provide the code behind if needed

How does the V8 engine know the diffrence between primitive and object?

I saw an answer of a question it says

As a general rule, in JavaScript all values, all objects, and all of their properties are stored on the heap.

So i started searching and i found this page it says

JavaScript values in V8 are represented as objects and allocated on the V8 heap, no matter if they are objects, arrays, numbers or strings. This allows us to represent any value as a pointer to an object.

and from the book : Speaking JavaScript

Primitive Values

The following are all of the primitive values (or primitives for short):

  • Booleans: true, false (see “Booleans” on page 12)
  • Numbers: 1736, 1.351 (see “Numbers” on page 14)
  • Strings: ‘abc’, “abc” (see “Strings” on page 15)
  • Two “nonvalues”: undefined, null (see “undefined and null” on page 10)

Primitives have the following characteristics:

Compared by value

The “content” is compared:

3 === 3

true

'abc' === 'abc'

true

Always immutable

Properties can’t be changed, added, or removed:

var str = 'abc';
str.length = 1; // try to change property `length`
str.length
// ⇒ no effect
3
str.foo = 3; // try to create property `foo`
str.foo
// ⇒ no effect, unknown property
undefined

(Reading an unknown property always returns undefined.)

Objects

All nonprimitive values are objects. The most common kinds of objects are:

  • Plain objects, which can be created by object literals (see “Single Objects” on page 25):
{
  firstName: 'Jane',
  lastName: 'Doe'
}

The preceding object has two properties: the value of property firstName is ‘Jane’
and the value of property lastName is ‘Doe’.

  • Arrays, which can be created by array literals (see “Arrays” on page 28):
[ 'apple', 'banana', 'cherry' ]

The preceding array has three elements that can be accessed via numeric indices.
For example, the index of ‘apple’ is 0.

  • Regular expressions, which can be created by regular expression literals (see “Regular
    Expressions” on page 31):
/^a+b+$/

Objects have the following characteristics:

Compared by reference

Identities are compared; every value has its own identity:

{} === {}
false
// two different empty objects
var obj1 = {};
var obj2 = obj1;
obj1 === obj2
true

Mutable by default

You can normally freely change, add, and remove properties (see “Single Objects” on page 25):

var obj = {};
obj.foo = 123; // add property `foo`
obj.foo
123

So my qusetion : Engine must know the value is a primative or object to know which characteristics will be applied. V8 engine represents any value as a pointer to an object.

So How does the V8 engine know the diffrence between primitive and object ( both are references ) ?

I think that
the pointer (reference) has a part that contains the primitive value itself ( for example if the primitive value is “hello” the pointer (reference) will contain “hello” ) if this part is empty the V8 engine will know this pointer (reference) points to an object
or the pointer has a part and this part works like a flag and that part tells the V8 engine if this pointer (reference) points to an object or this pointer (reference) points to a primitive value

Java/JSP – Minecraft server giving random error out of the blue, IllegalStateException [closed]

I am running a minecraft server with mods, and ran into this error –

[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [iceberg] Starting version check at https://mc-update-check.anthonyhilyard.com/520110
[16:33:13] [Forge Version Check/WARN] [ne.mi.fm.VersionChecker/]: Failed to process update information
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
        at com.google.gson.Gson.fromJson(Gson.java:1226) ~[gson-2.10.jar%2372!/:?] {re:mixin}
        at com.google.gson.Gson.fromJson(Gson.java:1124) ~[gson-2.10.jar%2372!/:?] {re:mixin}
        at com.google.gson.Gson.fromJson(Gson.java:1034) ~[gson-2.10.jar%2372!/:?] {re:mixin}
        at com.google.gson.Gson.fromJson(Gson.java:969) ~[gson-2.10.jar%2372!/:?] {re:mixin}
        at net.minecraftforge.fml.VersionChecker$1.process(VersionChecker.java:183) ~[fmlcore-1.20.1-47.3.0.jar%23634!/:?] {}
        at java.lang.Iterable.forEach(Iterable.java:75) ~[?:?] {re:mixin}
        at net.minecraftforge.fml.VersionChecker$1.run(VersionChecker.java:114) ~[fmlcore-1.20.1-47.3.0.jar%23634!/:?] {}
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
        at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:393) ~[gson-2.10.jar%2372!/:?] {}
        at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:182) ~[gson-2.10.jar%2372!/:?] {}
        at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:144) ~[gson-2.10.jar%2372!/:?] {}
        at com.google.gson.Gson.fromJson(Gson.java:1214) ~[gson-2.10.jar%2372!/:?] {re:mixin}
        ... 6 more
[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [supplementaries] Starting version check at https://raw.githubusercontent.com/MehVahdJukaar/Supplementaries/1.20/forge/update.json
[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [supplementaries] Found status: BETA Current: 1.20-2.8.17 Target: null
[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [create_pattern_schematics] Starting version check at https://raw.githubusercontent.com/cakeGit/Pattern-Schematics-Multiloader/1.20.1/forge-updates.json
[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [create_pattern_schematics] Found status: AHEAD Current: 1.1.15+forge-1.20.1 Target: null
[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [packetfixer] Starting version check at https://api.modrinth.com/updates/packet-fixer/forge_updates.json
[16:33:13] [Forge Version Check/INFO] [ne.mi.fm.VersionChecker/]: [packetfixer] Found status: UP_TO_DATE Current: 1.4.2 Target: null

I am curious if anyone has any suggestions on what is causing this/how to fix it?

I have tried reinstalling the iceberg mod, as well as deleting it’s configs, as I think that’s the problem mod but i’m not entirely sure.

Referencing class in function decorator call

I’m trying to pass a parameter to a decorator that references it’s own class:

export class SomeClass {
  public async handleError(error: Error): Promise<void> {
    // ... treating errors
  }

  @treat(SomeClass.prototype.handleError) // <- error here
  public async doSomething(): Promise<void> {
    // ... doing something
  }
}

But I’m getting this error:

ReferenceError: Cannot access 'SomeClass' before initialization

Is there anyway to do that or will I have to send the name of the treating function and find it inside the decorator?

JavaScript JSON.parse(JSON.Stringify([])) returns string instead of Object [closed]

I encountered strange behavior with the JSON.parse and JSON.stringify functions on one particular website, and I can’t figure out why this is happening. Running a snippet

typeof JSON.parse(JSON.stringify([1,3,4]))

on the tab with this site returns a result as a string (when it should be an object), but on all other tabs, it returns an object. There are no extensions enabled. A double JSON.parse (on the problematic tab) helps typeof JSON.parse(JSON.parse(JSON.stringify([1,3,4]))) , but it doesn’t explain where the issue originates. I suspect that some scripts might be loading on the problematic page, altering the function’s behavior, but I’m unsure how to check for this. JSON.stringify.toString() and JSON.parse.toString() returns native code in both cases.

What other checks can I perform? Which direction should I investigate, and what specifically should I look into?

Fetching HTML of a website is returning an error

Im trying to fetch the HTML of a website with the fetch() function but i can’t get it to work.

This is what I’ve seen being used but it doesnt seem to work for me:

fetch('website_here')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.text();
  })
  .then(html => {
    console.log(html); // Logs the HTML content of the page
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

Im getting this error: There has been a problem with your fetch operation: Error: Network response was not ok

How to detemine and handle cyclic dependencies that cause a function to not be found

Sometimes the code base I work with is very messy and sometimes I run into a problem where

Caused By: TypeError: <FUNCTION NAME HERE> is not a function

When in fact, it is a function that my IDE can even go to if i click on it or even if method is in same directory.

I learned sometime ago that sometimes if files / packages get a bit to hairy and im importing one module (file) and another and both are used and imported else where at same time, it can cause some cyclic dependency issue and the solution is to move out or extract out one of the functions or move around the files differently.

Now the error doesn’t say it is a cyclic dependency issue but i learned this by stack overflow and refactoring the files.

One issue is, this doesnt show up until run time and hard to detect so I am wondering if there is a better way to detect and handle these issues?

Thank you

Twilio Voice SDK Client Hanging Up Instantly

I am using Vue as my frontend. I am looking to integrate with Twilio’s Voice SDK to place outgoing calls and receiving incoming calls. I have setup my TwilML app, etc. and the plumbing of my token from my backend to the frontend. I am able to place a call to a hardcoded number, I hear a ringtone, browser asks for microphone permissions, but afterwards it instantaneously hangs up. I noticed the thread here:Twilio JS client hanging up immediately

I followed several of the answers, but to no avail.

Here is my current code:

Twilio Component (.vue):

<template>
  <div class="twilio-call">
    <button @click="makeCall" :disabled="isCalling">
      {{ isCalling ? "Calling..." : "Call" }}
    </button>
  </div>
</template>

<script>
import * as messagingApi from "../../../api/messaging.js";
import * as twilioVoiceSDK from "../../../utils/twilio.js"

export default {
  name: "TwilioCall",
  data() {
    return {
      twilioToken:
        "", 
      toNumber: "+1HardcodedNumber", 
      isCalling: false,
    };
  },
  methods: {
    async makeCall() {
      this.twilioToken = await messagingApi.getTwilioToken();

      if (this.isCalling) return;

      try {
        this.isCalling = true;

        // Initialize Twilio Device
        if (!twilioVoiceSDK.getDevice()) {
          twilioVoiceSDK.createDevice(this.twilioToken);

          // Handle error events
          twilioVoiceSDK.getDevice().on("error", (error) => {
            console.error("Twilio Error:", error);
            this.isCalling = false;
          });
        }

        // Register the Twilio device
        await twilioVoiceSDK.getDevice().register();

        // Make a call to the hardcoded number
        const callParams = { To: this.toNumber };
        const call = await twilioVoiceSDK.getDevice().connect(callParams);

        // Handle disconnect event
        call.on("disconnect", () => {
          this.isCalling = false;
          console.log("Call disconnected");
        });

        // Add event listeners to capture detailed logs
        twilioVoiceSDK.getDevice().on("ready", () =>
          console.log("Twilio Device is ready.")
        );
        twilioVoiceSDK.getDevice().on("error", (error) =>
          console.error("Twilio Device Error:", error)
        );
        twilioVoiceSDK.getDevice().on("connect", (conn) =>
          console.log("Twilio Connection established:", conn)
        );
        twilioVoiceSDK.getDevice().on("disconnect", (conn) =>
          console.log("Twilio Connection disconnected:", conn)
        );
        twilioVoiceSDK.getDevice().on("incoming", (conn) =>
          console.log("Incoming call:", conn)
        );

        console.log("Calling:", this.toNumber);
      } catch (error) {
        console.error("Error making call:", error);
        this.isCalling = false;
      }
    },
  },
};
</script>

<style scoped>
.twilio-call {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>

Twilio.js in utils

import { Device } from '@twilio/voice-sdk';

/**
 * Do NOT bind this object in Vue. Vue wraps proxies around it and that causes issues.
 *
 * @type { import('@twilio/voice-sdk').Device }
 */
let device = null;

/**
 * @param {String} token
 * @returns {Device}
 */
export function createDevice(token) {
    return device = new Device(token, {
        // See https://www.twilio.com/docs/voice/sdks/javascript/twiliodevice#deviceoptions
        logLevel: 0,
        // Set Opus as our preferred codec. Opus generally performs better, requiring less bandwidth and
        // providing better audio quality in restrained network conditions.
        codecPreferences: ['opus', 'pcmu'],
    });
}

/**
 * @returns { import('@twilio/voice-sdk').Device }
 */
export function getDevice() {
    return device;
}

Any help would be greatly appreciated!