#javascript

posts tagged #javascript

0

A React-like JS Framework with Web Components

preview

IMPORTANT DISCLAIMER: This is my own project. Im am using AI. Its important to get that out of the way… because its the key reason for why YOU SHOULD NOT USE IT. Im not trying to promote “yet another ui framework”, this is an investigation to see what is possible. Its unreviewed, unaudited and far from finished. Nobody else should be using this. This framework is intended for myself on my own projects. It is provided open-source for transparency, testing and demo purposes only.

I was investigating an idea i had about JSX-like syntax for webcomponents after some experience with Lit. I am sharing this here because it might be interesting/educational.

Lit is a nice lightweight UI framework, but i didnt like that it was using class-based components. It can support React with a wrapper, buts React is fundamentally an abstraction away from the DOM.

Vue has a nice approach but i prefer working with the syntax that React uses. I find it more intuitive for debugging and deterministic rendering. I wondered if with webcomponents, i could create a UI framework that didnt need to be transpiled.

My intentions with this framework is to get to a reasonable level of stability, to then replace React on some of my existing projects. I made a start by creating some basic reusable ui components components to be built with the js framework. Aiming for something like Material UI.

I can then compound that slop down into some basic UI demos:

To better demonstrate the pure-javascript and no-transpilation approach, i created an example repo of using a minimal amount of tooling for a PWA. The aim here is to keep the application logic in readable js and abstract the framework logic away from the developer.

To simplify things for myself, i added something similar to module-federation where i can fetch the dim/core dependencies as remote statics from github-pages instead of publishing to npm. The approach has tradoffs worth considering and is still a work-in-progress.

The disclaimer above is always worth repeating. Im aiming for a post like this to be like “building in public”. If interesting to anyone, i hope its inviting to take a look. It’s hard to determine if / when its a good time to share, so best to get it out there sooner for any outstanding issues i may have overlooked.

IMPORTANT DISCLAIMER: This is my own project. Im am using AI. Its important to get that out of the way… because its the key reason for why YOU SHOULD NOT USE IT. Im not trying to promote “yet another ui framework”, this is an investigation to see what is possible. Its unreviewed, unaudited and far from finished. Nobody else should be using this. This framework is intended for myself on my own projects. It is provided open-source for transparency, testing and demo purposes only.

I was investigating an idea i had about JSX-like syntax for webcomponents after some experience with Lit. I am sharing this here because it might be interesting/educational.

Lit is a nice lightweight UI framework, but i didnt like that it was using class-based components. It can support React with a wrapper, buts React is fundamentally an abstraction away from the DOM.

Vue has a nice approach but i prefer working with the syntax that React uses. I find it more intuitive for debugging and deterministic rendering. I wondered if with webcomponents, i could create a UI framework that didnt need to be transpiled.

My intentions with this framework is to get to a reasonable level of stability, to then replace React on some of my existing projects. I made a start by creating some basic reusable ui components components to be built with the js framework. Aiming for something like Material UI.

I can then compound that slop down into some basic UI demos:

To better demonstrate the pure-javascript and no-transpilation approach, i created an example repo of using a minimal amount of tooling for a PWA. The aim here is to keep the application logic in readable js and abstract the framework logic away from the developer.

To simplify things for myself, i added something similar to module-federation where i can fetch the dim/core dependencies as remote statics from github-pages instead of publishing to npm. The approach has tradoffs worth considering and is still a work-in-progress.

The disclaimer above is always worth repeating. Im aiming for a post like this to be like “building in public”. If interesting to anyone, i hope its inviting to take a look. It’s hard to determine if / when its a good time to share, so best to get it out there sooner for any outstanding issues i may have overlooked.

0

Binance error -1021 in Node.js: two messages, two different fixes

preview

Binance error -1021 looks like one problem, but it comes in two messages that need different fixes:

  • “Timestamp for this request was 1000ms ahead of the server’s time.”
  • “Timestamp for this request is outside of the recvWindow.”

Binance accepts a signed request only if timestamp < serverTime + 1000 and serverTime - timestamp <= recvWindow. So there is a fixed one-second tolerance for clocks that run fast, and a configurable window (5000 ms by default, 60000 ms at most) for requests that arrive late.

“1000ms ahead” is a clock problem. Increasing recvWindow does nothing for it. Sync the machine’s clock with NTP (on Linux, check timedatectl; on Windows, resync the time service), then try again.

“Outside of the recvWindow” means the request took too long between signing and arriving, or your clock runs slow. Fix the clock first. Only then consider a slightly larger recvWindow, and keep it small, because Binance recommends 5000 ms or less.

Two common bugs cause both messages in Node.js:

  • Sending seconds instead of milliseconds. Use Date.now(), not Math.floor(Date.now() / 1000).
  • Building the timestamp once and reusing it for later requests. Create it for each request.

If you use the binance npm package (an open-source SDK we maintain, from the same maintainers as the bybit-api and okx-api JavaScript SDKs, with over 4.5 million npm downloads across 10+ SDKs), it adds the timestamp and signature for you, with recvWindow set to 5000 by default. You can change it per client:

import { MainClient } from 'binance';

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY,
  api_secret: process.env.BINANCE_API_SECRET,
  recvWindow: 5000, // the default; raise it only for a genuinely slow link
});

const account = await client.getAccountInformation();
console.log(account.balances.length);

The SDK also has an optional time-sync mechanism (disableTimeSync: false), but it is off by default and we don’t recommend it. A correct system clock is the real fix.

More detail:

Disclosure: we maintain the binance SDK.

Binance error -1021 looks like one problem, but it comes in two messages that need different fixes:

  • “Timestamp for this request was 1000ms ahead of the server’s time.”
  • “Timestamp for this request is outside of the recvWindow.”

Binance accepts a signed request only if timestamp < serverTime + 1000 and serverTime - timestamp <= recvWindow. So there is a fixed one-second tolerance for clocks that run fast, and a configurable window (5000 ms by default, 60000 ms at most) for requests that arrive late.

“1000ms ahead” is a clock problem. Increasing recvWindow does nothing for it. Sync the machine’s clock with NTP (on Linux, check timedatectl; on Windows, resync the time service), then try again.

“Outside of the recvWindow” means the request took too long between signing and arriving, or your clock runs slow. Fix the clock first. Only then consider a slightly larger recvWindow, and keep it small, because Binance recommends 5000 ms or less.

Two common bugs cause both messages in Node.js:

  • Sending seconds instead of milliseconds. Use Date.now(), not Math.floor(Date.now() / 1000).
  • Building the timestamp once and reusing it for later requests. Create it for each request.

If you use the binance npm package (an open-source SDK we maintain, from the same maintainers as the bybit-api and okx-api JavaScript SDKs, with over 4.5 million npm downloads across 10+ SDKs), it adds the timestamp and signature for you, with recvWindow set to 5000 by default. You can change it per client:

import { MainClient } from 'binance';

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY,
  api_secret: process.env.BINANCE_API_SECRET,
  recvWindow: 5000, // the default; raise it only for a genuinely slow link
});

const account = await client.getAccountInformation();
console.log(account.balances.length);

The SDK also has an optional time-sync mechanism (disableTimeSync: false), but it is off by default and we don’t recommend it. A correct system clock is the real fix.

More detail:

Disclosure: we maintain the binance SDK.

0

Oxlint JS Plugins: Your Custom ESLint Rules No Longer Keep You on ESLint

Dan Holloran Oxlint JS Plugins: Your Custom ESLint Rules No Longer Keep You on ESLint danholloran.me
preview

Oxlint’s JavaScript plugin support hit alpha in March 2026, and the Oxc team’s claim is that roughly 80% of ESLint users can switch and have it “just work.” The interesting part is how they got there: an ESLint-compatible plugin API running beside the native Rust rules, so you keep your rules and only pay JavaScript prices for the rules that actually need JavaScript.

Oxlint’s JavaScript plugin support hit alpha in March 2026, and the Oxc team’s claim is that roughly 80% of ESLint users can switch and have it “just work.” The interesting part is how they got there: an ESLint-compatible plugin API running beside the native Rust rules, so you keep your rules and only pay JavaScript prices for the rules that actually need JavaScript.

0

How to Gaslight JavaScript Programmers

preview

It turns out, JavaScript provides a method of “trapping” nearly any operation on an object - property access, assignment, enumeration, and even property deletion. How? Via a Proxy. Think of a Proxy as a “hook” or “middleware” that can be used to gaslight the caller into seeing the proxied object any way you want them to see it. When you wrap an object in a Proxy, you can do almost anything you imagine - hide properties like I did with goodbye above, invent new “virtual” properties, or even make operations on properties “cursed”:

It turns out, JavaScript provides a method of “trapping” nearly any operation on an object - property access, assignment, enumeration, and even property deletion. How? Via a Proxy. Think of a Proxy as a “hook” or “middleware” that can be used to gaslight the caller into seeing the proxied object any way you want them to see it. When you wrap an object in a Proxy, you can do almost anything you imagine - hide properties like I did with goodbye above, invent new “virtual” properties, or even make operations on properties “cursed”:

0

limito: a 1 KB rate limiter for Node, Bun, Deno and Workers

GitHub GitHub - SleepyDaniel/limito: Fast, tiny rate limiter for Node, Bun, Deno and the edge github.com
preview

I made a small rate limiter for JS. It’s about 1 KB, has no dependencies and runs on Node, Bun, Deno and Cloudflare Workers.

It uses GCRA, so each key is just one timestamp instead of a counter plus a timer. Nothing runs in the background. Keys you’ve already seen don’t allocate either, since the timestamps live in a Float64Array.

import { limito } from 'limito'

const rl = limito({ limit: 100, window: '1m' })
const wait = rl('user:42') // 0 if allowed, otherwise ms to wait

There’s also a Redis version for when you have multiple servers, and small middlewares for Express and Hono.

MIT licensed, still early (0.5). Feedback and bug reports welcome.

I made a small rate limiter for JS. It’s about 1 KB, has no dependencies and runs on Node, Bun, Deno and Cloudflare Workers.

It uses GCRA, so each key is just one timestamp instead of a counter plus a timer. Nothing runs in the background. Keys you’ve already seen don’t allocate either, since the timestamps live in a Float64Array.

import { limito } from 'limito'

const rl = limito({ limit: 100, window: '1m' })
const wait = rl('user:42') // 0 if allowed, otherwise ms to wait

There’s also a Redis version for when you have multiple servers, and small middlewares for Express and Hono.

MIT licensed, still early (0.5). Feedback and bug reports welcome.

0

way to change a color to transparency on a png

preview

hello

I need to create in javascript something to change a color to transparent, on PNG
I’d like to create a form that, when I post a picture, everything white should be transformed to transparent and generated as a new PNG, however this white is coming from a picture so it won’t be exactly white
but contrast are good since this will pictures of text written on a white page
maybe some king of green screen algo

any ideas on how to do that ?

hello

I need to create in javascript something to change a color to transparent, on PNG
I’d like to create a form that, when I post a picture, everything white should be transformed to transparent and generated as a new PNG, however this white is coming from a picture so it won’t be exactly white
but contrast are good since this will pictures of text written on a white page
maybe some king of green screen algo

any ideas on how to do that ?

0

Why an idempotency key doesn't stop a double charge

preview

Most of us implement idempotency the same way the first time. Check whether you’ve seen the key, and if not, do the work and store the key so the next request knows:

app.post("/charge", async (req, res) => {
  const key = req.get("Idempotency-Key");
  if (await redis.get(key)) { 
      return res.json(JSON.parse(await redis.get(`${key}:result`)));
  }

  const result = await chargeCard(req.body);      // real money leaves here
  await redis.set(key, "done");
  await redis.set(`${key}:result`, JSON.stringify(result));
  res.json(result);
});

It reviews fine. Then two things happen in production.

Two retries arrive at the same moment. Both reach the get before either reaches the set, so both charge the card. A load test finds this one if you go looking.

The process dies after chargeCard and before redis.set. The money moved, the key was never written, and the retry charges again. This one you can’t easily reproduce on purpose, and it happens on its own during any deploy.

Fixing the first properly means the check and the write have to be one atomic operation, so exactly one caller wins. That creates the next problem: the winner can die holding the key, so the claim needs a lease that expires. Which creates another: the “dead” worker might just be slow, wake up, and overwrite the real result with its stale one. So the write needs a fencing token that the reclaimer invalidates.

I got tired of rewriting that, so it’s a library now:

import express from "express";
import { idempotency } from "idemkit/express";
import { RedisBackend } from "idemkit/redis";

const app = express();
app.use(idempotency({ backend: await RedisBackend.fromUrl(process.env.REDIS_URL) }));

app.post("/charge", async (req, res) => {
  res.status(201).json(await chargeCard(req.body));   // runs once per Idempotency-Key
});

Same thing works for queue consumers (SQS, Kafka, RabbitMQ, BullMQ) and plain function calls. Redis, Postgres, Mongo, DynamoDB or in memory. Zero dependencies, Apache-2.0.

github.com/idemkit/idemkit

If you find it useful, a star would be much appreciated.

Most of us implement idempotency the same way the first time. Check whether you’ve seen the key, and if not, do the work and store the key so the next request knows:

app.post("/charge", async (req, res) => {
  const key = req.get("Idempotency-Key");
  if (await redis.get(key)) { 
      return res.json(JSON.parse(await redis.get(`${key}:result`)));
  }

  const result = await chargeCard(req.body);      // real money leaves here
  await redis.set(key, "done");
  await redis.set(`${key}:result`, JSON.stringify(result));
  res.json(result);
});

It reviews fine. Then two things happen in production.

Two retries arrive at the same moment. Both reach the get before either reaches the set, so both charge the card. A load test finds this one if you go looking.

The process dies after chargeCard and before redis.set. The money moved, the key was never written, and the retry charges again. This one you can’t easily reproduce on purpose, and it happens on its own during any deploy.

Fixing the first properly means the check and the write have to be one atomic operation, so exactly one caller wins. That creates the next problem: the winner can die holding the key, so the claim needs a lease that expires. Which creates another: the “dead” worker might just be slow, wake up, and overwrite the real result with its stale one. So the write needs a fencing token that the reclaimer invalidates.

I got tired of rewriting that, so it’s a library now:

import express from "express";
import { idempotency } from "idemkit/express";
import { RedisBackend } from "idemkit/redis";

const app = express();
app.use(idempotency({ backend: await RedisBackend.fromUrl(process.env.REDIS_URL) }));

app.post("/charge", async (req, res) => {
  res.status(201).json(await chargeCard(req.body));   // runs once per Idempotency-Key
});

Same thing works for queue consumers (SQS, Kafka, RabbitMQ, BullMQ) and plain function calls. Redis, Postgres, Mongo, DynamoDB or in memory. Zero dependencies, Apache-2.0.

github.com/idemkit/idemkit

If you find it useful, a star would be much appreciated.

0

evikit: Preact SSR framework for small web apps using a node:sqlite ORM

Codeberg.org evikit codeberg.org
preview

I like the full-stack framework SvelteKit. It inspired me to write something more minimal, even brutalist, based on Preact, a few small focused modules popular in its ecosystem, and Vite.

There’s intentionally not much API. Documentation entirely fits in a long but straightforward README. Like the Django tutorial, it guides you through writing an application using all the primary features of the EviKit framework.

I wanted to use standard modern JavaScript as supported by Node.js 24+ directly. With strict JSDoc type annotations. So no separate language server is needed - you can use Emacs, Kate or any other modern editor of your choice that supports typescript-language-server. Linting using ESLint and Prettier also works without extra plugins.

There’s neither JSX nor a new templating language to learn. There are JS helpers for creating common elements, e.g. you write p({ class: “nav” }, a({ href: “/” }, “Home”)). You use JS map for loops and ternary operator for conditional constructs.

I focused on old-school urlencoded and multipart forms, and the app is rendered on the server, so apps should remain partially accessible even when JS doesn’t load. At the same time, an EviKit app is a proper SPA, hydrated with client-side routing (with URLPattern-based server-side counterpart) and conveniently made dynamic with React-style hooks.

I want to ease the writing of bots and interoperability with low-code tools. So apps generate OpenAPI (Swagger) specification for your API.

Input/output validation using Valibot is first-class. Type checking catches if e.g. after an upgrade your API starts returning something different from your declaration. With less need for boilerplate unit tests, you can focus on end-to-end replication of real user scenarios.

Most apps need databases. Why not try the node:sqlite built-in? I made it easy to declare a schema using the same Valibot helpers that I use for API declaration. EviKit keeps the database in a standard location following the XDG specification. You can save file uploads as SQLite blobs.

Translatable strings of your UI can be automatically extracted using GNU Gettext tools, well-known in Django, WordPress and Linux desktop app ecosystems. I recomment the Poedit editor for translating the resulting .po files. Your app is shown in the browser language if there’s a matching translation, with English fallbacks.

For styling, I wanted to avoid non-standard hacks that make Node.js “import” CSS, so I recommend going with daisyUI and the now usual Tailwind CSS.

There’s a real-world FOSS app using EviKit: Lanquiz, that lets you import Kahoot quizzes and self-host them in LAN from a laptop during blackouts.

Non-goals: cloud deployment (I only target VPS and LAN apps), competition with Pracht scope (I guess there are bugs to fix, but the framework is more or less finished).

Last but not least, no “AI” whatsoever was used for writing the framework. I don’t have a hardline stance, it’s more that I don’t see how it could be useful for this tool. LLMs let people come up with ever mode code and boilerplate, while I want radically less of it. If you’d like to contribute, let’s keep it simple and human.

I like the full-stack framework SvelteKit. It inspired me to write something more minimal, even brutalist, based on Preact, a few small focused modules popular in its ecosystem, and Vite.

There’s intentionally not much API. Documentation entirely fits in a long but straightforward README. Like the Django tutorial, it guides you through writing an application using all the primary features of the EviKit framework.

I wanted to use standard modern JavaScript as supported by Node.js 24+ directly. With strict JSDoc type annotations. So no separate language server is needed - you can use Emacs, Kate or any other modern editor of your choice that supports typescript-language-server. Linting using ESLint and Prettier also works without extra plugins.

There’s neither JSX nor a new templating language to learn. There are JS helpers for creating common elements, e.g. you write p({ class: “nav” }, a({ href: “/” }, “Home”)). You use JS map for loops and ternary operator for conditional constructs.

I focused on old-school urlencoded and multipart forms, and the app is rendered on the server, so apps should remain partially accessible even when JS doesn’t load. At the same time, an EviKit app is a proper SPA, hydrated with client-side routing (with URLPattern-based server-side counterpart) and conveniently made dynamic with React-style hooks.

I want to ease the writing of bots and interoperability with low-code tools. So apps generate OpenAPI (Swagger) specification for your API.

Input/output validation using Valibot is first-class. Type checking catches if e.g. after an upgrade your API starts returning something different from your declaration. With less need for boilerplate unit tests, you can focus on end-to-end replication of real user scenarios.

Most apps need databases. Why not try the node:sqlite built-in? I made it easy to declare a schema using the same Valibot helpers that I use for API declaration. EviKit keeps the database in a standard location following the XDG specification. You can save file uploads as SQLite blobs.

Translatable strings of your UI can be automatically extracted using GNU Gettext tools, well-known in Django, WordPress and Linux desktop app ecosystems. I recomment the Poedit editor for translating the resulting .po files. Your app is shown in the browser language if there’s a matching translation, with English fallbacks.

For styling, I wanted to avoid non-standard hacks that make Node.js “import” CSS, so I recommend going with daisyUI and the now usual Tailwind CSS.

There’s a real-world FOSS app using EviKit: Lanquiz, that lets you import Kahoot quizzes and self-host them in LAN from a laptop during blackouts.

Non-goals: cloud deployment (I only target VPS and LAN apps), competition with Pracht scope (I guess there are bugs to fix, but the framework is more or less finished).

Last but not least, no “AI” whatsoever was used for writing the framework. I don’t have a hardline stance, it’s more that I don’t see how it could be useful for this tool. LLMs let people come up with ever mode code and boilerplate, while I want radically less of it. If you’d like to contribute, let’s keep it simple and human.