Prettier Custom Plugin

Using React, Typescript, Vite, Prettier.

I’m trying to customize some formatting options in Prettier, specifically have the opening curly bracket { in functions one line below their signature like so:

function myFunc()
{

}

instead of

function myFunc() {

}

I got the following:

import { doc } from 'prettier';
import parserBabel from 'prettier/parser-babel';

function printFunctionDeclaration(path, options, print) {
  const node = path.getValue();

  if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
    const parts = [
        print(path.get("id")), // Print the function name
        "(",
        print(path.get("params")),
        ")",
    ];

    // Add the opening curly brace on a new line
    parts.push([doc.builders.line, "{"]);
    
    // Print the body of the function
    parts.push(print(path.get("body")));

    return doc.builders.indent(parts);
  }

  return null;
}

export default {
    parsers: {
        astFormat: "babel",
        babel: {
          parse: (text, parsers, options) => {
            const ast = parserBabel.parsers.babel.parse(text, parsers, options);
            return ast;
          },
        },
      },
  printers: {
    astFormat: "babel",
    babel: {
        print(path, options, print) {
            const node = path.getValue();
            
            // Check for function declaration or arrow function expression
            if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
              return printFunctionDeclaration(path, options, print);
            }
      
            // Default printing for other nodes
            return print(path);
          },
    }
  },
};

But after linking it to my .prettierrc file and trying it, it gives me the following error: Error: astFormat is required.

IIS won’t handle the static file properly for nodejs-express and vite-react app. No static file found (index…. .js and index…. cs -> 404.0)

I have created frontend using react-vite and backend using nodejs-express.js. Done npm run build for production build of frontend and served the static build using express.static()

Whenever I host my app on IIS using iisnode and url-rewrite. The app can fetch index.html correctly but as soon as index.html being loaded the IIS can route the static files needed but index.html

<configuration> 
    <system.webServer>
  
     <handlers>
       <add name="iisnode" path="server.js" verb="*" modules="iisnode" />
     </handlers>
  
     <rewrite>
       <rules>
       
         <rule name="nodejs">
           <match url="(.*)" />
           <conditions>
             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
           </conditions>
           <action type="Rewrite" url="server.js" />
         </rule>

        <rule name="ReactRouter Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          </conditions>
          <action type="Rewrite" url="/frontend/dist/index.html" />
        </rule>

       </rules>
     </rewrite>
  
     <security>
       <requestFiltering>
         <hiddenSegments>
           <add segment="node_modules" />
           <add segment="iisnode" />
         </hiddenSegments>
       </requestFiltering>
     </security>
     </system.webServer> 
 </configuration>

server.js:

import path from "path";
import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";

import authRoutes from './backend/routes/auth.routes.js'
import messageRoutes from "./backend/routes/message.routes.js";
import userRoutes from './backend/routes/user.routes.js';

import connectToMongoDB from "./backend/db/connectToMongoDB.js";
import { app, server } from "./backend/socket/socket.js";

dotenv.config();


// Initialize express application

const PORT = process.env.PORT || 5000;
const __dirname =  path.resolve();

// Load environment variables from .env file

/*
        MIDDLEWARE SECTION
*/
app.use(express.json()); //to parse the incoming requests with JSON payloads (from: req.body)
app.use(cookieParser());


// app.use->(  Middleware to handle routes starting with /api/auth/)
app.use("/api/auth", authRoutes);  //authentication routes
app.use("/api/messages", messageRoutes); //get & send:id message
app.use("/api/users", userRoutes);  //get users

app.use(express.static(path.join(__dirname, "/frontend/dist")));

app.get("*", (req, res) => {
        res.sendFile(path.join(__dirname, "/frontend", "dist", "index.html"));
})



/*
        SERVER SECTION
*/

// Start the server and listen on the specified port
server.listen(PORT, '0.0.0.0',() => {
    connectToMongoDB();
    console.log(`Server is running on PORT: http://localhost:${PORT}`)

});

I have hosted the app as subsite under default website and the error I always get is:
No .js and .css file found. I tried making changes in web.config still no reaults.


localhost/chat

http://localhost/assets/index-qBCe9vKe.js

JavaScript shuffle elements but track original index or use modulus to insert them into parent markup

I have the following markup:

<div class="">
  <div class="tiled-gallery__gallery">
    <div class="tiled-gallery__row columns-1">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-dan/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-jessica/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=1132%2C1132&amp;strip=info&amp;ssl=1 1132w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/rebecca-2/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=1333%2C1333&amp;strip=info&amp;ssl=1 1333w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-2/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-4/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-teram-test-3/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-1/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
  </div>
</div>

I want to be able to shuffle each item: <div class="tiled-gallery__item"> into a random position, however the issue I have is that the first item has a parent container which specifies 1 column columns-1 although most of the markup uses the 2 column layout class columns-2.

I have written a basic shuffle using this javascript:

const shuffleElems = () => {
  const wrapper = document.querySelector(".tiled-gallery__gallery");
  const items = wrapper.querySelectorAll(
    ".tiled-gallery__row .tiled-gallery__col"
  );

  for (var i = items.length; i >= 0; i--) {
    wrapper.appendChild(items[(Math.random() * i) | 0]);
  }
};

shuffleElems();

This works in that it will rearrange the items, but it could add a single item into a column that should take two. So I assume I need some way of tracking the original index and the new one, and either using a modulus, or checking the parent class. Or possibly shuffling everything in the column-2 classes and then just swap the single row at the very end?

I hope this makes sense, all of the code is in codesandbox.

I will add a screenshot shortly.

How to use sendBeacon for tracking checkout status before page redirect in JavaScript?

I have a function submitOrderRequestForm that submits form data via an AJAX call and redirects the user to another page upon a successful response. I want to track the status “REQUEST_FLOW” using the sendBeacon API before the page redirects.

Here is my current code:

function submitOrderRequestForm() {
            $('#mobile_number').val($("#phone-number").intlTelInput("getNumber"));
            $('#contact_number').val($("#phone-number").intlTelInput("getNumber"));
            $('#orderType').val('order_request');
            // $('#consentEmailValue').val($("#consentEmail").is(":checked") ? 1 : 0);
            // $('#consentSMSValue').val($("#consentSMS").is(":checked") ? 1 : 0);
            $('#consentBothValue').val($("#consentBoth").is(":checked") ? 1 : 0);

            getToken();
            // $("#continueBtn").prop("disabled",true);
            $.ajax({
                url: "{{URL::route('item.borrow-post',$shoppingCart->id)}}",
                type: "post",
                async: false,
                data: $("#reservationForm").serialize(),
                success: function (data) {
                    if (data.type=='success') {
                        window.location.href = "{{URL::route('submit-order-request')}}";
                        checkout_tracking_status = "REQUEST_FLOW";
                    }
                },
}

I want to use the sendBeacon API to send tracking data to the server for the checkout_tracking_status = “REQUEST_FLOW” event. However, I’m not sure how to implement this correctly to ensure the beacon sends the data reliably before the page redirects.

Where should I place the sendBeacon call to ensure it executes before the redirect?
How can I structure the data payload for sendBeacon?

Any guidance or examples would be greatly appreciated.

SVG Sprite not working in the consuming app

I implemented an SVG sprite file generation for all my SVG icons. It works and I have a fully working file within components/icons/sprites/icons.svg. Then inside my Index.tsx file I have:

import { SvgIcon } from '@mui/material';

<SvgIcon
  viewBox={viewBox}
  sx={sx}
  aria-label={label}
  data-test={dataTest}
  {...rest}
>
  <use xlinkHref={`${sprite}#${iconName}`} />
</SvgIcon>'

It all works fine in my Storybook, so I’m sure that this implementation should be fine. If I inspect the element in the storybook it is:

<use xlink:href="static/media/icons.svg#text-aa"></use>

The issue starts to exist when I’m building my package. It struggles in the consuming app to get the icon. In my webpack config for the package I have:

{
  test: /components/icons/sprites/icons.svg$/,
  type: 'asset/resource',
  generator: {
    filename: 'sprites/icons.svg',
    publicPath: '/',
  },
},

I also have publicPath: '/', within the webpack output object.

This ends with such selector in the consuming app:

<use xlink:href="/assets/icons.svg#warning"></use>

It renders nothing

If I expect node_modules, the file is there – node_modules/@company/packageName/dist/assets/icons.svg

I can see in the Chrome network tab that it’s trying to reach /assets/icons.svg but ends up with 404 Not Found.

When I remove the publicPath: '/', from the webpack output object, and just keep:

{
  test: /components/icons/sprites/icons.svg$/,
  type: 'asset/resource',
},

for the rules object, I end up with some svg generated file in the main dist folder in the consuming app node modules: node_modules/@company/packageName/dist/db6b1fc5dea1759a88ef.svg

And then within the app running in the browser:

<use xlink:href="file:///Users/marcus/Desktop/repos/sso-playground/node_modules/@company/packageName/dist/components/badge/../../db6b1fc5dea1759a88ef.svg#warning"></use>

This time it is

Not allowed to load local resource:

Basically I’ve already experimented a lot with publicPath or filename and the build bundle in the consuming app follow all the settings, however then the import does not work. I’m a bit surprised, because there is another package running in my app, also design system with icons sprite from it, there’s no special config in the app for that and the icons just work out of the box with such tag:

<use xlink:href="/images/vendor/@company/anotherPackage/components/icons/icons.svg?16c5895e4b93fe53247be390dfbb7ba1#alert-circle"></use>

What am I missing, what could be done to get the icons working in my consuming app?

How to print in italic using Docxtemplater libary

I’m trying to generate a Microsoft Word Document using docxtemplater library https://www.npmjs.com/package/docxtemplater. Here is how my code would look like (using in browser):

<script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.49.0/docxtemplater.js"></script>
<script src="https://unpkg.com/[email protected]/dist/pizzip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
<script src="https://unpkg.com/[email protected]/dist/pizzip-utils.js"></script>

    <script>
        function loadFile(url, callback) {
            PizZipUtils.getBinaryContent(url, callback);
        }

        window.onload = function generate() {
        const data = "<i>some text with italic</i>";

        const file = "http://file-url";

        loadFile(file, function (error, content) {
            if (error) {
                throw error;
            }
            const zip = new PizZip(content);
            const doc = new window.docxtemplater(zip, {
                paragraphLoop: true,
                linebreaks: true,
            });

            doc.render({
                "data":data
            });

            const blob = doc.getZip().generate({
                type: "blob",
                mimeType:
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                compression: "DEFLATE",
            });
 
            saveAs(blob, "output.docx");

        });
    }
    </script>

When i look at the word output, i expect it to look like “some text with italic”, instead of

<i>some text with italic</i>

How can i make text in the word output italic using docxtemplater library?

How to keep the date exactly as specified in the input string (without any implicit UTC conversion) [duplicate]

I am facing an issue while writing a function with [dayjs][1] library.

The problem I am trying to solve, is to extract the date part (only) from a given date-time string and ensure that the value of date is not changed.

For example: "Thu Jan 30 2225 23:45:46 GMT-0800 (Pacific Standard Time)" should result in "2225-01-30" in YYYY-MM-DD format, but with the solution I attempted (code snippet below), I am getting output as "2225-01-31".

In summary, I do not need any time-conversion to be applied, while extracting the date part. I have also tried to include dayjs/plugin/timezone but the date change happens before itself, when dayjs(date) is invoked.

Code snippet:

const date = "Thu Jan 30 2225 23:45:46 GMT-0800 (Pacific Standard Time)";
const formattedDate = dayjs(date).format("YYYY-MM-DD");
console.log(formattedDate);
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>

Any insights on this will be helpful. I am open to writing a native JavaScript function as well or consider other libraries.

I have also gone through similar question asked before, and have tried the suggestions and still not getting the desired outcome.

Triggering a script from an existing script in Big Commerce

Before I implement a script in Script Manager, I’m just wondering if there’s a way to trigger a script after an existing one (under the hood) has been fired.

So I would like to trigger my custom script after a product option has been selected on the product page. I’m currently working on the script but it occurred to me that this would be the best practice.

Thanks all

Stroke canvas elements as if they’re one element

I have a canvas with multiple circles and want to stroke them as if they are 1.

as you can see, it is all drawn on their own

  context.beginPath();
  context.fillStyle = "#F9F8F3";
  context.arc(0, height/6*4, width/6, 0, Math.PI*2);
  context.arc(width/6*1.9, height/6*4.45, width/6*1.25, 0, Math.PI*2);
  context.arc(width/6*3.75, height, width/6, 0, Math.PI*2);
  context.arc(width/6*5.5, height/6*4, width/5, 0, Math.PI*2);
  context.stroke();

image with all circles being stroked

its supposed to look kind of like this
example for desired output

How can I get the input from an input tag and use it back in the code? [duplicate]

I am trying to make a dice where you can choose the minimum and maximum values. Currently, I have tried different ideas, but they don’t work. It messes up the other code, and I don’t know why.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="styles.css" />
  <script src="styles.js"></script>
  <title>Dice Roller</title>
</head>

<body>
  <h1>Dice Roller</h1>
  <p>Can't decide on what to eat? Or what to do? Our dice roller is perfect for this.</p>
  <div>
    <label>Minimum:</label><input type="number" min="1" class="input min" id="min"><p> </p><label>Maximum:</label><input type="number" min="2" class="input max" id="max">
  </div><br>
  <div>
  <section>
    <button class="roll-button" type="button" onclick="rollDice(document.getElementById(`min`).value, document.getElementById(`max`).value)">Roll</button>
    <h1 id="output"></h1>
  </section>
  <section>
  <script type="text/javascript">
       function rollDice(a = 1, b = 6) {
          dice = Math.floor(Math.random() * (b - a + 1)) + a
          console.log(dice);
          document.getElementById("output").innerHTML = dice;
        }
          </script>
  </section>
  </div>
</body>

</html>

How can I get the input from the min and max values and use it in the JavaScript function in a way that it works? (starter coder, sorry if it is an easy question)

Laravel nwidart “$CLASSServiceProvider” not found

After installing the package nwidart/laravel-modules and configuring it with the commands provided in the package documentation, I encounter the following error after creating a simple module:

Class “ModulesPhpMyAdminProvidersPhpMyAdminServiceProvider” not
found

Here are the changes made to the composer.json file to use the module:

{
    "$schema": "https://getcomposer.org/schema.json",
    "name": "laravel/laravel",
    //........................
    "require": {
        "php": "^8.2",
        //........................
        "nwidart/laravel-modules": "^11.1"
    },
    "require-dev": {
        //........................
    },
    "autoload": {
        "psr-4": {
            "Modules\": "Modules/",
            //........................
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    //........................
    "extra": {
        "laravel": {
            "dont-discover": [
            ],
            "merge-plugin": {
                "include": [
                    "Modules/*/composer.json"
                ]
            }
        }
    },
    //........................
    "minimum-stability": "dev",
    "prefer-stable": true
}

After running the command composer dump-autoload, I expected to access the route within the phpmyadmin module using the address localhost:8000/phpmyadmin:
php

Route::get('phpmyadmin', function () {
    dd('test');
})->name('phpmyadmin');

What I’ve noticed is that in the file bootstrap/cache/module.php, the service provider for the module I created is defined as follows:

<?php return array (
  'providers' => 
  array (
    0 => 'Modules\PhpMyAdmin\Providers\PhpMyAdminServiceProvider',
  ),
  'eager' => 
  array (
    0 => 'Modules\PhpMyAdmin\Providers\PhpMyAdminServiceProvider',
  ),
  'deferred' => 
  array (
  ),
);

When I remove these service providers, the error goes away, but the issue of accessing the page still persists, resulting in a 404 error, and this route is not visible in the Laravel routes list when I run:

php artisan route:list

Feel free to post this on Stack Overflow for assistance!

Authorize.net refund Transaction error: has invalid child element ‘payment’ in namespace

On the sandbox API endpoint i try to refund a previously valid transaction (120053733345) with the following createTransactionRequest array (converted into JSON):

Array
(
    [merchantAuthentication] => Array
        (
            [name] => mytestname
            [transactionKey] => mytestkey
        )
    [refId] => 1041-352205
    [transactionRequest] => Array
        (
            [transactionType] => refundTransaction
            [amount] => 29.00
            [currencyCode] => CAD
            [refTransId] => 120053733345
            [payment] => Array
                (
                    [creditCard] => Array
                        (
                            [cardNumber] => 5121212121212124
                            [expirationDate] => 2028-01
                        )
                )
        )
)

While the authCaptureTransaction operation works fine, i receive an error with the refundTransaction operation:

The element ‘transactionRequest’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’ has invalid child element ‘payment’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’. List of possible elements expected: ‘splitTenderId, order, lineItems, tax, duty, shipping, taxExempt, poNumber, customer, billTo, shipTo, customerIP, cardholderAuthentication, retail, employeeId, transactionSettings, userFields, surcharge, merchantDescriptor, subMerchant, tip, processingOptions, subsequentAuthInformation, otherTax, shipFrom, authorizationIndicatorType’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’.

I’ve tried to follow the instruction in
https://developer.authorize.net/api/reference/index.html#payment-transactions-refund-a-transaction
and
Is it possible to refund a transaction in Authorize.Net sandbox account?
but with no success.

How to show a message, redirect user, and generate PDF in the background?

I need to implement a flow where, when a user clicks the “Generate PDF” button, a message appears saying “Your PDF is being generated,” and the user is redirected to the homepage. Meanwhile, the PDF generation continues in the background on the server.

I’m using JavaScript for the frontend and PHP on the backend. The PDF generation may take some time, so I want to ensure the user isn’t blocked during this process. I plan to send an asynchronous request to start PDF generation and then redirect the user. On the backend, I want to run the PDF generation in the background (via a worker or exec()).

What’s the best approach to implement this without blocking the user’s experience?

Facebook Ad replacing UTMs with FBCLID

I am promoting landing pages with forms through Facebook Ads.

The form is designed to capture UTM parameters passed in the landing page URL.
In the Facebook Ad, I add the UTM parameters using the appropriate fields. However, when I click on the ad and get redirected to my landing page, I notice that Facebook modifies the URL, removing the UTM parameters and adding the “fbclid” parameter instead.

How can I retrieve the UTM parameters?

I see that landing pages created by platforms like EverAd are still able to capture them, but after analyzing the landing page code, it’s unclear how they manage to do it.

Use of LDAP in PHP generates an error when the wrong password is supplied

I’m using the LDAP functions in PHP.

My code works quite well, but a problem arises when the user types the wrong password.

In that case my expectation is a message that says “wrong password inserted” (I created a function for it) but instead of it PHP returns an error that blocks the script execution.

Warning: ldap_bind(): Unable to bind to server: Invalid credentials in
/var/www/html/0functions/logon.php on line 83

Warning: ldap_search(): Search: Operations error in
/var/www/html/0functions/logon.php on line 85

Fatal error: Uncaught TypeError: ldap_get_entries(): Argument #2
($result) must be of type LDAPResult, false given in
/var/www/html/0functions/logon.php:86 Stack trace: #0
/var/www/html/0functions/logon.php(86):
ldap_get_entries(Object(LDAPConnection), false) #1
/var/www/html/login.php(22): logdap(‘USER’, ‘PWD’) #2 {main} thrown in
/var/www/html/0functions/logon.php on line 86

My perception is that this is a DLL error. Is there a way to get around this error and let my function go to the end?

It is annoying for the user because they receive the error 500 and get stuck without understanding that it is just because the password is wrong.