Service worker and OIDC

I am using a service worker to cache the static resources for my website. The cache name is key’ed by the Last-Modified header so that I can do a rolling deployment. The user will only ever be shown a full set of static resource from one release. After the release is complete, the service worker cache is updated.

The fetch event looks like this:

event.respondWith(caches.match(event.request).then(r => r || fetch(event.request)))

I’ve hit an issue where I’m getting a 401 when visiting the site root /. It’s a cache miss (which is a problem in itself but I can look at that separately) and is calling fetch().

The site is protected by OIDC where authentication is done via SPNEGO (i.e. there is no login screen). The OIDC access token lifespan has a maximum of 12 hours (including any refreshes).

I assume the fetch is unable to follow the redirects to re-fetch an access token (for the OIDC protocol), but I can’t figure out what I need to do to solve it.

Sidebar: Had it been a cache hit, I would have had an invalid token anyways…I feel like OIDC with service worker should be a solved pattern but I couldn’t find anything via Google.

App claims out of memory despite enough allocated

I am running Windows 11 64bit with 32GB of RAM. No other processes are running. I init Node.js using this command

node index.js --max-old-space-size=16384

In task manager I see 50% memory usage. So why does the app crash at 4GB?

<--- Last few GCs --->
[11724:000001EAD7670000]  9250018 ms: Mark-Compact 4044.3 (4144.3) -> 4043.1 (4143.9) MB, pooled: 0 MB, 2449.39 / 0.00 ms  (average mu = 0.398, current mu = 0.204) allocation failure; scavenge might not succeed
[11724:000001EAD7670000]  9252815 ms: Mark-Compact 4044.5 (4144.3) -> 4043.7 (4144.6) MB, pooled: 0 MB, 2216.51 / 0.00 ms  (average mu = 0.314, current mu = 0.207) allocation failure; scavenge might not succeed
<--- JS stacktrace --->
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

forEach on array of DOM elements fails with “Cannot read properties of undefined” but for loop works — why?

I’m trying to attach event listeners to two DOM elements like this (both elements exist):

const signout = document.getElementById('logout');
const signoutMobile = document.getElementById('logout-mobile');

[signout, signoutMobile].forEach(el => {
  if (el) {
    el.addEventListener('click', async () => {
      await logout();
    });
  }
});

async function logout() {
    // fetch logic
}

However, this throws an error in the browser console:

Uncaught TypeError: Cannot read properties of undefined (reading 'logout-mobile')

But when I rewrite the same logic using a for loop, it works perfectly:

const elements = [signout, signoutMobile];
for (let i = 0; i < elements.length; i++) {
  const el = elements[i];
  if (el) {
    el.addEventListener('click', async () => {
      await logout();
    });
  }
}

Why does the .forEach() approach throw an error, while the for loop works fine?

Furthermore, when I place the logout function before the .foreach block, … it works!

Works:

    1. logout declaration, 2)forEach
    1. for, 2) logout declaration
    1. logout declaration, 2) for

Doesn’t work:

    1. forEach, 2) logout declaration

Additional info:

  • Both snippets are placed in the same script file.
  • The variables signout and signoutMobile are assigned using document.getElementById() before the iteration.
  • The script is loaded with defer.
  • The elements with IDs logout and logout-mobile exist in the DOM.
  • The logout function is declared and works properly.

I suspect it has something to do with when the variables are assigned relative to the iteration.

What am I missing here?

Note: chatGPT fails to fix this, or explain the problem.

How to secure client-side code from server side

I have a React web app where I display some D3 diagram. The user can download this diagram as a JPG file. I want to control from the server side (Node.js) who is able to download it and who isn’t.

There is a library that makes this download feature available. I have to pass the root svg element to this library and it completes the rest. As everything is on client side I am not sure how I could control from the server side who has access to this download feature.

I could call a server-side feature before executing the import-to-JPG feature but it is client-side code so this call (to check who has access) can be hacked or just ignored so I presume it is not a very good solution.

What I thought of is to download the import-to-JPG library/code from the server side only in those cases when the user has access, otherwise this library/code won’t exist (i.e. the download code won’t exist in the client code but only on the server). So when the user would click on the download button then the import-to-JPG code would be downloaded from server and executed. However I am not sure if it can be done and how.

Is there any other solution to control this client-side behaviour from the server?

Getting extra space between lines of text (not due to line height)

I have this code which was supposed to highlight some code wrapped in “` (like you wrap snippets on stack overflow):

function Pre({ children, ...props }) {
  ....
  const highlightedHTML = highlight(codeString);

  return <pre {...props} className="" dangerouslySetInnerHTML={{ __html: highlightedHTML }} />;
}

However, the HTML it generates has extra space between the lines.

See the generated element here: https://stackblitz.com/edit/web-platform-2msddmqs?file=index.html

Don’t pay attention to styles and classes in the sandbox they aren’t even defined in CSS.

Why am I getting these extra lines can someone explain?

And how can I amend above that code so that I don’t run into that problem?


highlight is a function from library sugar-high. And this Pre is part of using this where you just say that this component will be used when you want to generate code blocks.

How do I implement pagination support in laravel-seo-sitemap?

I’m using the laravel-seo-sitemap package to generate sitemap XML files in a Laravel 10 application.

I have a paginated blog route like this:

Route::prefix('/blog')->group(function () {
    Route::get('/', [BlogController::class, 'index'])
        ->name('support.blog.index')
        ->priority('0.6')
        ->sitemap();
});

This correctly adds /blog to the sitemap, but I also want to include paginated versions like /blog?page=2, /blog?page=3, etc., since those contain unique and crawlable content (e.g. paginated archive listings).

How can I configure the package to generate sitemap entries for each page of the pagination?

Ideally, I’d like to specify:

  • The total number of pages dynamically (from a model or query)
  • The route pattern to apply pagination (/blog?page=2, /blog?page=3, …)

Is there a way to extend the sitemap generator with a custom SitemapItemTemplate or hook into the route’s sitemap registration?

Any example or guidance would be appreciated.

https://github.com/VeiligLanceren-nl/laravel-seo-sitemap

I already did try to use the template but it didn’t work out as wished.
I was expecting that this will solve the issue but it not worked out

Combine multiple rows in from and to columns into one

I have two tables

table1

id    from     to
02    900      990
01    1005     1030
02    2190     3050
03    4150     4200

table2

id    from     to
01    1005     1030
02    2190     3000
02    3001     3050
03    4150     4175

What I am trying to do is for each row in table1, I want to check if it exists in table2 even if its in multiple rows in table2 but continuous.

In the above example for id 01 in table1 its easy to get id 01 in table2 as from and to are same. I got that.

But I also want for id 02 (the third row, not the first one). All from and to for id 02 in table1 are there in table2 but as they are in multiple rows I can’t get them.

Id 03 will not come as its not complete in table2

table1 can have multiple rows with same id but from and to range will be different and there will never be an overlap.

table2 can have the same id of table1 distributed in more than 2 rows also.

I am fetching rows from table1 and trying to find the from and to range in table2 so I have all the fields of the particular row from tabe1 in an array.

What I am expecting is just exists yes/no.

I am using PHP/ORACLE.

Any leads would be appreciated.

Thanks.

Below is the small working snippet if from and to are single row in table1 and table2.

$or1 = oci_parse($o_con, "select * from table1");
oci_execute($or1);
$count_1 = oci_fetch_all ($or1, $ow1 , 0, -1, OCI_FETCHSTATEMENT_BY_ROW);

for ($i = 0; $i < $count_1; $i++)
{
    $id = $or1[$i]['ID'];
    $begin = $or1[$i]['FROM'];
    $end = $or1[$i]['TO'];
    $or2= oci_parse($o_con, "select * from table2 where from = $begin and to = $end and id= '$id'");
    oci_execute($or2);
    $count_2 = oci_fetch_all ($or2, $ow2 , 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
    if ($count_2 == 0 ) { $color="red";} else { $color="green"; }
}

cURL error 23 when downloading nativephp/mobile in Laravel

I’m trying to install the nativephp/mobile package in my Laravel project using Composer, but I keep getting a cURL error 23. Here’s the command I’m running

composer require nativephp/mobile --ignore-platform-req=ext-zip

I’m using the –ignore-platform-req=ext-zip flag because I don’t have the ZIP extension installed (could this be related?)
I also tried Clearing Composer cache but still not working.

Remove strike through line and prepend text to price

I’ve got these two snippets from a good source they both work.
But I’m trying to hide strike out only not rrp price. Also I’m trying to prepend rrp and sales price with text. So both rrp and sales price should show, but both be prependeded withncustom text.

add_filter(‘woocommerce_get_price_html’, ‘hide_strikethrough_price’, 100, 2);

function hide_strikethrough_price($price, $product) {
if (is_admin() || !is_shop() && !is_product() && !is_product_category()) {
    return $price;
}

if ($product->is_on_sale() && $product->get_regular_price() !== $product->get_price()) {
    return wc_price($product->get_sale_price());
}

return $price;

}

if( !function_exists("add_custom_text_prices") ) {
function add_custom_text_prices( $price, $product ) {
    // Text
    $text_regular_price = __("Non-members: ");
    $text_final_price = __("Members only: ");

    if ( $product->is_on_sale() ) {
        $has_sale_text = array(
          '<del>' => '<del>' . $text_regular_price,
          '<ins>' => '<br>'.$text_final_price.'<ins>'
        );
        $return_string = str_replace(
            array_keys( $has_sale_text ), 
            array_values( $has_sale_text ), 
            $price
        );

        return $return_string;
    }
    return $text_regular_price . $price;
}
add_filter( 'woocommerce_get_price_html', 'add_custom_text_prices', 100, 2 );

}

Website Looks perfect in Firefox but Fails in Chrome [closed]

I created a website for my son’s business in 2007. It looks perfect in Firefox but the Left column with the Menu and a graphic, instead of floating to the left of the main column, have shifted down below the content of the page. It’s pretty old school. My son died last weekend and I thought I’d fire it up for his friends and our family could see his logging business and photos.
Here is the website:
https://clairepoulton.com/fosters-logging

I did template it using PHP HEREDOC

I believe the problem is in the css file but I can’t find it even using the Chrome Inspector

https://clairepoulton.com/fosters-logging/styles/fosters.css

Why am I getting “req.body is not set” when using @apollo/server with expressMiddleware in Apollo Server, even after adding express.json() before it?

Why am I getting “req.body is not set” when using @apollo/server with expressMiddleware in Apollo Server v4, even after adding express.json() or bodyParser.json() before it?

import express from "express";
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
import cors from "cors";

async function startServer() {
  const app = express();
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(cors());

  const server = new ApolloServer({
    typeDefs: `#graphql
        type Todo{
        id : ID!
        Title : String!
        Completed : Boolean
        }
        type Query{
            getTodos : [Todo]
        }
    `,
    resolvers: {},
  });

  await server.start();
  app.use("/graphql", expressMiddleware(server));

  app.listen(8000, () => {
    console.log("server is running on port 8000");
  });
}

startServer();

I followed the official Apollo Server v4 setup using @apollo/server and expressMiddleware. I added express.json() and even bodyParser.json() before the middleware. I expected the GraphQL server to parse JSON requests correctly. However, I keep getting this error:
“req.body is not set; this probably means you forgot to set up the ‘json’ middleware…”

Resolving errors with recharts graph in nextjs, incorrect type/null

I am new to nextJS and I’m experiencing multiple errors when trying to add a graph/chart using recharts

The main error is : Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, key, props, _owner, _store}). If you meant to render a collection of children, use an array instead.

This error occurs when I use the code from this recharts example :

<LineChart width={400} height={400} data={data} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
  <XAxis dataKey="name" />
  <Tooltip />
  <CartesianGrid stroke="#f5f5f5" />
  <Line type="monotone" dataKey="uv" stroke="#ff7300" yAxisId={0} />
  <Line type="monotone" dataKey="pv" stroke="#387908" yAxisId={1} />
</LineChart>

I have also tried adding a barchart using this code :

<ResponsiveContainer width="100%" height={300}>
    <BarChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip formatter={(value) => `$${value}`} />
        <Legend />
        <Bar dataKey="price" fill="#8884d8" />
    </BarChart>
</ResponsiveContainer>

The above code gives a different error : TypeError: resolveDispatcher() is null

I have tried adjusting the graph code and the data but the error remains regardless of the changes I make

This is the sample data I tried to use with the line chart code

const data = [
    { name: 'Original Price', price: 100 },
    { name: 'Reduced Price', price: 50 },
];

The LineChart code is within a div within a main within the main return

How to call hook after delete mutation?

In my react app, I would like to navigate to another page after I execute GQL delete mutation using Apollo. This mutation is called from inside a modal popup:

const [deleteDeck, { loading }] = useMutation(DELETE_DECK, {
    onCompleted() { (Navigate("/decks")) },
    onError: (error) => { setError(error.graphQLErrors[0].message)}
  });

The mutation finished successfully but I get the following error:

Invalid hook call. Hooks can only be called inside of the body of a function component.

What am I doing wrong?

OnClick works only once

HTML:

<svg id="settings-icon" xmlns="http://www.w3.org/2000/svg" height="90px" viewBox="0 -960 960 960" width="40px" fill="#FFF"><path d="(thepath)" onclick='settings()'></svg>

JS:

function settings() {alert("hello")}

The alert only happens the first time when clicked. Afterwards I would need to reload then the alert will show again. Or not the alert wouldn’t show after the first time.

Help greatly appreciated.

EDIT: it works but only sometimes. when i click theres bout a 50% chance it alerts