Is it possible to bundle a dynamic import into single file in webpack?

I am developing a js module, which use the “crypto” module. I want single package supporting different platforms such as node, web, react-native etc. So I use dynamic import to import “crypto”, if fail then I fallback to an old version of crypto-js which does not use any native API.

e.g. when generating random bytes

import crypto from "crypto-js";

async function randomBytes(length: number): Promise<Buffer> {
    
    try{
        const nodeCrypto = (await import("crypto")).default;
        return nodeCrypto.randomBytes(length);
    }
    catch(err){
        log.error("randomBytes error using crypto module, fallback to crypto-js", err);
    }

    return Buffer.from(crypto.lib.WordArray.random(length).words.flatMap(it => [it & 0xff, (it >> 8) & 0xff, (it >> 16) & 0xff, (it >> 24) & 0xff]))
}

The problem is when I bundle UMD for web using webpack (with “crypto” fallback to “crypto-browserify” ), I get 2 files even with splitChunks: false. I think this is because of dynamic import (correct me if I am wrong). If this is the case, is there any method to bundle or convert the dynamic import into static import, in webpack level, so that it only output single file?

View XPS and PDF in browser

I need to organize document viewing in the browser. The documents can be in PDF and XPS formats. I tried using an iframe. PDF documents are displayed, but XPS ones are immediately downloaded. Is there any way to display XPS files?

My JS:

function displayFile(element) {
  var objectId = element.id.substring('categories_'.length);
  var project_id = '{{ project.id }}';
  var url = `/pilot_doc/get_file/${objectId}/${project_id}/`;
  var options = {
      method: 'GET', 
      headers: {
          'Accept': 'application/octet-stream' 
      }
  };

  fetch(url, options)
      .then(response => {
          if (!response.ok) {
              throw new Error('Network response was not ok');
          }
          return response.json(); 
      })
      .then(data => {
          if (data.status === 'success') {
            var byteCharacters = atob(data.file);
            var byteNumbers = new Array(byteCharacters.length);
            for (var i = 0; i < byteCharacters.length; i++) {
              byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            fileName = data.file_name;
            fileExtension = getFileExtension(fileName);
            console.log(fileExtension);
            var contentType;
            if (fileExtension === 'pdf') {
              contentType = 'application/pdf';
            } else if (fileExtension === 'xps') {
              contentType = 'application/vnd.ms-xpsdocument';
            } else {
              throw new Error('Unsupported file format');
            }
            var blob = new Blob([byteArray], {type: contentType}); 
            var url = URL.createObjectURL(blob);
            var iframe = document.createElement('iframe');
            var docBox = document.querySelector('.box.doc');
            var heightInPixels = docBox.offsetHeight;
            iframe.style.width = "100%";
            iframe.style.height = `${heightInPixels-30}px`; 
            iframe.src = url; 
            docBox.innerHTML = ''; 
            docBox.appendChild(iframe); 
          }
      })
      .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          alert('Ошибка при загрузке файла: ' + error.message);
      });
}

What makes an empty object qualify as an Iterable or Array-like object?

Given Array.from takes an iterable or array-like object as it’s first argument, why does it not throw an error when passed an empty object, like this:

let emptyObject = Array.from( {} )

At iterable is defined as an object that implements the iterable protocol or the iterator protocol. An empty object seemingly does neither:

let emptyObject = {}

console.log(emptyObject[Symbol.iterator])
console.log(emptyObject['next'])
console.log(Array.from(emptyObject))

An Array-like object has a length property and can be indexed (ref). An empty object does not have a length property.

let emptyObject = {}

console.log(emptyObject['length'])
console.log(Array.from(emptyObject))

How does an empty object qualify?

customRecord not defined SuiteScript 2.0 UE

Attempting to write a script to pull data from a record into a new record type using an User Event Script. I continue to get an this error: ReferenceError: {custom record type} is not defined at object.afterSubmit.

This is the portion of the code that is failing. This first line is specifically being called out as not defining the custom record. I have it set to the custom record internal ID name.

// Set the value for the ‘Name” field
customrecord_sample_record_wo_log.setValue({
fieldid: ‘name’,
Value: ‘DEL-001’

How to capture form input using Selenium WebDriver and JavaScript

Generally when there’s an already existing credential like username, we use:

driver.findElement(By.name("username")).sendKeys("Rick")

But, what if there’s an input that the user enters in the form. How to capture that input using JavaScript? I mean, instead of “Rick”, I want to capture whatever the user enters and then send that to the sendKeys() method.

Add seatmap for every show_ID

I really don’t know what am I gonna do because I have no expertise when it comes to javascript.
My problems are,
How can I add a seatmap for every movieshow that I have
How can I make checked seats be saved as reserverved and cannot be unchecked by other customers

 ```
<script>

$(document).ready(function() {
    for(i=1;i<=4;i++)
    {
      for(j=1;j<=10;j++)
      {
        $('#seat_chart').append('<div class="col-md-2 mt-2 mb-2 ml-2 mr-2 text-center" style="background-color:grey;color:white"><input class="movie-chair" type="checkbox" id="seat" value="R'+(i+'S'+j)+'" name="seat_chart[]" class="mr-2  col-md-2 mb-2" onclick="checkboxtotal();" >R'+(i+'S'+j)+'</div>')
      }

    }
});





function change_option(mvalue)
{

    sessionStorage.setItem("movie_id_of_option", mvalue.value);
    alert(sessionStorage.getItem('movie_id_of_option'));

   
}
 



function checkboxtotal()
{
   var seat=[];
   $('input[name="seat_chart[]"]:checked').each(function(){
       seat.push($(this).val());
   });

   var st=seat.length;
   document.getElementById('no_ticket').value=st;
   var total="Php. "+(st*600);
   $('#price_details').text(total);

  // $('#seat_details').text(seat.join(", "));
   $('#seat_dt').val(seat.join(", "));
}

</script>

The issue about importing variable into javascript in AppleScript

I meet an issue when I imported a variable(got from javascript A)to the javascript B, here is my script code:

tell application "Safari"
    tell tab 6 of window 1
        set varA to do JavaScript "document.getElementById('idA').textContent." as string
    end tell
    tell tab 7 of window 1
        do JavaScript "
        document.getElementById('idB').value=" & varA & ";"
    end tell
end tell

And I found when varA contains non-number content, it couldn’t be imported to the input filed of “idB”, I don’t understand…..

I tried to return var A in AppleScript, it shows the value correctly. And I tried to

"set varB do JavaScript "
document.getElementById('idB').value=" & varA & ";"

When I return var B in AppleScript, it shows error number -2753.

I hope the script can help me to get the value from webpage A and input it to a specific input filed on webpage B.

How to Create a Page Rotation Effect using CSS Transforms on Scroll?

<html>
<div className="z-10 w-full  h-screen bg-[#192c4e] scroll-transform-container ">
<div className='flex justify-center items-center w-full'>
</div>
</div>
</html>
<style>
.scroll-transform-container {    
transform-origin: left top ;    
transition: transform .5s ease-out;
animation: 1ms rotate45DegAnimation;
animation-direction: alternate;
animation-timeline: scroll(block nearest);    
perspective-origin: left top;
}

@keyframes rotate45DegAnimation {
0% {
transform: perspective(1000px) rotateY(90deg);
}

100% {
transform: perspective(1600px) rotateY(20deg);
}
}
</style>

I’m trying to implement a page rotation effect using CSS transforms, where a rectangle on the page starts off being perpendicular and, as the user scrolls down, gradually rotates to 45 degrees. I’ve been experimenting with the transform property,

but I’m encountering some issues in achieving the desired effect.

Reference – https://www.hexa3d.io/ —> 1st Section

Github – https://github.com/Aniruddha-Gade/next-app
Live – https://next-app-six-wine.vercel.app/

Formula fields library

Is there any javascript/jquery library for creating formulas fields

Iam researching whether there is plugin for creating formula fields using sql mathematical functions and logical functions .I want something that is similar to jquery query builder.

Tried to create a class for a button creating, but didn’t get it with Canvas Context

I’m creating a game, i started with the menu, i tried to create a object class called button (also tried it with function), i made it with canvas context 2D, it works all fine, but when i run the code, the buttons created doesn’t center it with translate, it kinda of does when i use it with only one of them, but when i create more it doesnt go for the center. The script below for more context:

`class Button{ //maybe change this for a function, try with another html code and see if it works
// Define the button properties that we will call to create a especified one.
constructor(color, textColor, name, x, y, width, height, fontSize){

    const textWidth = context.measureText(name).width //Define a especial variable of the text width that will debug in console.log
    
    // Define all button properties in constructor.
    this.color = color
    this.textColor = textColor
    this.name = name
    this.x = x
    this.y = y
    this.width = width
    this.height = height
    this.fontSize = fontSize
    
    let translateX = width/2
    let translateY = height/2
    
    //Define the button Style
    context.translate(translateX, translateY)
    context.fillStyle = color
    context.fillRect(x,y,width,height)
        
    //Define how the button text will be draw, (just put nothing at the creation of especified and it will not have a text on it.)  
    context.fillStyle = textColor
    context.font = "bold 14px arial"
    context.translate(width/2 - 14  ,height/2)
    context.fillText(name,x,y, fontSize) 
    
    //Debug
    console.log("The > " + "!" + name + "!" + " width is " + textWidth)
    console.log("The > " + "color of " + name + " is: " + color)
    console.log("The > " + "text color of " + name + " is: " + textColor)
    console.log("The > " + "position X of " + name + " is: " + x)
    console.log("The > " + "position Y of " + name + " is: " + y)
    console.log("The > " + "width of " + name + " is: " + width)
    console.log("The > " + "height of " + name + " is: " + height)
    console.log("The > " + "font size of " + name + " is: " + fontSize)
    console.log("The > " + "translate X of " + name + " is: " + translateX)
    console.log("The > " + "translate Y of " + name + " is: " + translateY)
    
}

}

function draw(){

    scene = level[0]

    context.fillStyle = "gray"
    context.fillRect(0,0,500,500)
    
    if(scene == level[0]){
        const start = new Button("white","black","start",500/2, 100, 100, 30, 30)
        const start0 = new Button("white","black","start1",500/2, 100, 100, 30, 30)
        const testZero = new Button("white","black","",500/2, 100, 100, 30, 30)
    }
    

}`

Thats the code, when i run it in my browser, it looks like this:

Here

Although the buttons have the same x and y, they change its x by little, and i dont know what it is. If you know, please tell me, i will be greatful 🙂

I expected it to go for the center of its origin, and simply go for the center with only (500/2), but it won’t.

openai npm package giving error on deployment

Im receiving this error in my backend when I go to deploy. I have never gotten this error only since I installed the openai package in the backend.

My node version is 20 so node:fs should work just fine. It also should be found because it’s built into node. I don’t import it anywhere, so I’m guessing the open ai package uses it or depends on it.

node:internal/modules/cjs/loader:927
  throw err;
  ^

Error: Cannot find module 'node:fs'
Require stack:
- /srv/node_modules/openai/_shims/node-runtime.js
- /srv/node_modules/openai/_shims/auto/runtime-node.js
- /srv/node_modules/openai/_shims/index.js
- /srv/node_modules/openai/streaming.js
- /srv/node_modules/openai/core.js
- /srv/node_modules/openai/index.js
- /srv/index.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:924:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:996:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/srv/node_modules/openai/_shims/node-runtime.js:37:19)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:996:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/srv/node_modules/openai/_shims/node-runtime.js',
    '/srv/node_modules/openai/_shims/auto/runtime-node.js',
    '/srv/node_modules/openai/_shims/index.js',
    '/srv/node_modules/openai/streaming.js',
    '/srv/node_modules/openai/core.js',
    '/srv/node_modules/openai/index.js',
    '/srv/index.js'
  ]
}
npm notice 
npm notice New major version of npm available! 7.7.6 -> 10.5.0
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v10.5.0>
npm notice Run `npm install -g [email protected]` to update!
npm notice

How do you find the stack trace of a JavaScript Promise that never resolves?

I’ve written an automated test in Jasmine that tests my asynchronous code. Somewhere in my code, a Promise fails to resolve/reject and Jasmine errors with a timeout:

  Message:
    Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)
  Stack:
        at <Jasmine>
        at listOnTimeout (node:internal/timers:573:17)
        at processTimers (node:internal/timers:514:7)

It’s not a matter of giving the promise more time. Increasing the timeout has the same effect but with a longer delay.

Unfortunately, that stack trace doesn’t lead me to the source of the problem. It’s a stack trace to the Jasmine code that interrupted my test, not the part of my code that was waiting to resolve. How do I see the latter?

I’m not sure how much Jasmine factors into a potential solution. For example, Java has ways to see all the threads in a program. Does Node.JS have something similar? Is there a library or node.js setting that makes promises more verbose?

I’m using node v20.10.0.

Regular expression that allows me to match all but the defined substring

I have the following string:

testInputs.abc_def.alpha=abc^ORtestVars.var23.nameISEMPTY^testInputs.alpha_bravo.more.otheroneCONTAINSsomething^testVars.anotherone!=abc^testVars.mYVar!=abc

I need it to match

testInputs.abc_def.alpha
testVars.var23.name
testInputs.alpha_bravo.more.otherone
testVars.anotherone
testVars.mYVar

I can match all occurences, but the problem is that it also matches some operators that it shouldnt:

ISEMPTY
CONTAINS

(And a slew of others like IN, NOT IN, etc.)

I have an array that I can join to create an alternation, but the issue is maintaining the match, without the prohibted substrings. As it stands now instead of

testVars.var23.name

I end up with

testVars.var23.nameISEMPTY

Similarly, I match testInputs.alpha_bravo.more.otheroneCONTAINS

The rules as it stands are:

  • Match can start with testInputs. or testVars.
  • Any alpha numeric, regardless of case, as well as underscores(_) and periods(.)
  • The substring after the testInputs or testVars can be any length
  • There can be multiple matches in a string
  • The match can also be in the form of {{var}} e.g {{testInputs.myinput}}=abc or {{testVars.my_var}}ISEMPTY, but I have left the above clear of that so it’s easier to read.

So far I have tried the following:

(({{)?(?:testInputs.|testVars.)[a-zA-Z0-9_.]+(}})?)

And tried a few variations of the lookahead/behind

(?!CONTAINS|ISEMPTY)

But have been unsuccessful in excluding the Invalid substrings, while still matching the piece of the match I’m looking for.

How to get complete barcode scanner input in single JS event?

I want to force all input from any devices to specific text box within anywhere of page.

So I write this code to handle keyboard input and barcode scanner input.

The event for keyboard is no problem, but I don’t know how to write the event for barcode scanner.

If I use keydown for barcode scanner, the event will be called every character, then I can get the last character only.

I expect there is an event for every single scan.

<input type=text id=in>
<script>
    var input = document.querySelector("#in")
    var body = document.querySelector("body")
    body.addEventListener("keydown", forKeyboard)
    body.addEventListener("???????", forBarcodeScanner)
    function forKeyboard(event){
        let printable = event.key.length === 1
        if(event.key === 'Delete'){
            input.value = ''
        }
        if(printable){
            input.value += event.key
        }
    }
    function forBarcodeScanner(event){
        input.value = ''
        input.value = event.key
        console.log(event.key)
    }
</script>