RSSAmplifier

Blog

Revath S Kumar

blog.revathskumar.comRSS feed ↗50 posts

Latest posts

waybar: custom module to help you refocus

Couple of months ago when I read the post How I hacked my clock to control my focus by Marc Päpper, It quickly became a daily driver for me. This small hack using a shell script helped me to get back to work quickly when ever I get distracted. I quickly realized that I needed something comparable with waybar after moving to Hyprland. Custom Module I want the module to be dead simple and use only…

hide your dotenv secrets from LLMs using pass

I have been using pass for a while to avoid credentials being saved into CLI history. AWS_SECRET = $( pass show project/dev/aws_secret ) < command > After reading about enveil project, I thought, rather than adding another tool into my arsenal, Why don’t I just use the tools I already have? TLDR: The pass extension and setup instructions can be found in the pass-env Codeberg repository. the bash…

update semantic version using bash script

For all of my JavaScript projects, I depend on the npm version command to update the version number for generating a release. So when I wanted to release my Zig project (clipz) , I was looking for something similar to update the version number in the build.zig.zon file. Since Zig doesn’t have any command equivalent to npm version , I decided to go with a simple shell script. The bash script…

zig : pass version from build.zig.zon file to runtime

In this blog post we will explore how to pass the options/values from the build to the project’s Zig code. To illustrate this, we will consider the example of reading the version from build.zig.zon at build and using it at runtime. Zig won’t allow us to import the build.zig.zon file in our main or other source files. So we need to get the value at build and expose it to our modules. use addOptions…

publish npm module with provenance statement

Provenance statements are a way to establish where a package was built and who published a package, which can increase supply-chain security and transparency for the packages. You can read about this in more detail in the npm documentation . Having a provenance statement doesn’t guarantee the package has no malicious code. Instead, npm provenance provides a verifiable link to the package’s source…

opt-out telemetry from cli tools

As most of the CLI tools/JavaScript frameworks started collecting telemetry data by default, I started looking into how I could easily opt out from these. Many of the tools support disabling the telemetry via environment variables. I therefore decided to compile these env variables from the various tools and frameworks in one place. # telemetry.fish # https://bun.com/docs/runtime/bunfig#telemetry…

Prisma : Extending model with custom methods

As a person coming from a Ruby on Rails background, I prefer ActiveRecord pattern to DataMapper . Obviously the choice will be based on the project and other criteria’s, but from my experience, most projects don’t require the complexity of Data Mapper. When I started using Prisma, one of the confusions for me was how to add a custom method to a model. Extending Prisma Client model object Prisma…

css: safe alignment of flex-items

The simple way to center a flex item is using center for justify-content or align-content . When we use center with dynamic flex items, there is a chance of data loss when the items overflow the alignment container. Safe alignment To avoid the data loss when the items overflow, we can use the safe keyword along with center justify-content : safe center Now this will help us center the items when…

PWA : receive file or text via native share

In this blog post, we will explore into how a PWA can receive files or text from the navite OS share functionality. By Using the Web Share Target API , a PWA can register with the OS as a share target and receive shared data. Updates to web manifest To register the PWA as share target, we need to add share_target into the web manifest. share_target : { action : " /share-target " , method : " GET "…

webassembly - passing string between zig and javascript

When working with webassembly (wasm) we only have numeric values. This means that if we need to handle strings, we need to handle them in raw binary data format using TypedArray & ArrayBuffer . If we want to pass complex data types between the web assembly (wasm) and the host JavaScript environment, we pass the memory pointer to shared memory and a length data. In this blog post we will learn how…

How to detect different JavaScript runtimes

As more and more JavaScript runtimes become popular, and each runtime has some subtle differences in how modules/functions behave , if we want to support our JavaScript code in these runtimes, we should be able to detect the runtime. Ideally we should check the supported feature, instead of the runtimes, but in case if we want to detect the runtimes themselves, here are the checks we can do if (…

Deno : url.domainToASCII behaves differently from nodejs

While working with @fedify/fedify today, I came across a bug where the .well-known/webfinger route was returning 404 . After some debugging and chatting with the @fedify/fedify team, I realised that this problem only happened when used with Node.js. Finally, after hours of debugging, I was able to identify the root cause as the behaviour of the url.domainToASCII . import { domainToASCII } from '…

JavaScript : understanding string normalize

Visualize different string normalization forms using string-normalize.surge.sh/?str=öé+ff Recently, When I was working on enhancing the search of Bender , I wanted to search words with characters like "ö" or "é" using normal characters like o and e . While looking into handling this case, I came across String.prototype.normalize String.prototype.normalize supports 4 types of normalization NFC :…

gjs : How to read from stdin in a gtk application

In this blog post, I will show you how to read from stdin in a GTK application written with gjs. Since I was already using greenclip (with rofi ) for clipboard history, I would like to use Bender in a similar way. greenclip print | bender . As a beginner to GJS-GTK, my first challenge was to bootstrap a GTK app and read the data from stdin. For the first prototype, I used the…

writing gjs gtk app in typescript

Recently I wanted to write a small GTK utility for personal use, and I was looking into writing it in TypeScript. The Gnome Builder bootstraps in JavaScript, so I was exploring the ways which I can set up the project without Gnome builder. In case you want to skip all the manual steps, and want to bootstrap the application (including packaging) in single command you can skip to Bootstrap using…

CSS: typesafe variables using @property

CSS @property allows developers to define variables with type checking and constraining, initial value and inherit rules. @property --custom-variable { syntax : '<color>' ; inherits : false ; initial-value : #000 ; } If we define a CSS variable without @propery , browser developer tools won’t give any feedback for the wrong values, instead, if we use @property like @property…

Git: tips I follow for better git commits

Git is more than just adding files and storing them. It’s about looking back in time and seeing changes or going back to old changes. In order to properly and easily revert the changes in git, we should plan it at the time of committing the changes. In order to make the revert easier, I personally prefer to organise commits into logical chunks. Also, in case if I need to revert a change, I should…

TypeScript - return and arguments type based on enum

Consider a simple function draw which can expect and enum for the type of the shape needs to draw as first argument and dimensions object as second argument. const SHAPE_TYPES = { CIRCLE : ' CIRCLE ' , SQUARE : ' SQUARE ' , TRIANGLE : ' TRIANGLE ' , } as const ; type ShapeTypesEnum = ( typeof SHAPE_TYPES )[ keyof typeof SHAPE_TYPES ]; interface Circle { radius : number ; } interface Square {…

jest : module mocking in es modules

When using CommonJS module system, we can jest.mock to mock the modules or functions. with jest.mock the mock statement will be hoisted automatically so we don’t need to worry about the import orders. But when it comes to ES Modules, we have to use the jest.unstable_mockModule This comes with 2 major differences it doesn’t hoist the mock statements factory method as second param is mandatory Since…

zig : basic progress indicator in terminal

Yesterday I thought of putting together my recent learning’s about ANSI escape codes and zig. In my last blog, I used ANSI escape codes to give color to the text in terminal. In this exercise, I will use [1A to erase start of line to the cursor so that I can build a basic progress indicator for the terminal. Disclaimer : This is for learning purposes only, if you like to use a progress indicator…

Gren : using ANSI escape codes

In this blog post, we will look into using ANSI escape sequences to give colors for the terminal outputs in Gren Lang . Standard escape codes are prefixed with \033 (Octal), ⁣ \x1B (Hex) or \u001B (Unicode) followed by the command. Gren Lang doesn’t support \0 or \x as part of the string. So the only option is to use \u (Unicode). In order to get some basic text in red color, we will be using…

Github : override language definitions

Recently, when I pushed some gren-lang code to GitHub, it was missing the syntax highlighting. Since GitHub recognises ELM and the same can be used for Gren, I was looking for ways to override the language definition on GitHub. That led me to the github-linguist/linguist , the library GitHub uses to detect the languages. Using the override strategies , I was able to get the syntax highlighting for…

npm run fuzzy auto-complete with preview using fzf

In my previous blog post, we discussed adding fuzzy search for curl options using fzf . In this post, we will add fuzzy completion to the npm run command by reading “scripts” from package.json in the current directory. This requires jq , to available on PATH . Helpers for sub-command Fzf _fzf_complete_COMMAND function will trigger on main command and not for sub commands like npm run . To support…

curl: fuzzy search options using fzf

Curl has more than 200 CLI options, and using classic autocomplete is not a great way to find those options. So, we will use the fzf, and its custom fuzzy completion API , _fzf_complete to easily find those options. _fzf_complete_curl () { _fzf_complete --header-lines = 1 --prompt = "curl> " -- " $@ " < < ( curl -h all ) } _fzf_complete_curl_post () { awk '{print $1}' | cut -d ',' -f -1 } Here is…

React : Testing file upload using testing library

In this post, we will look into writing a test case for file upload using the React testing library Select accepted file type In order to simulate file upload in test case, we will be using upload method from @testing-library/user-event . upload method will accept input element as the first argument and File object as the second. import userEvent from ' @testing-library/user-event ' ; import {…

TypeScript: add types for axios response data and error data

When using axios with TypeScript, one major problem we face is the types for the response data and error data. Consider the below function, which uses axios.post async function postHello () { try { const response = await axios . post ( ' /hello ' , {}); console . log ( response . data ); } catch ( error ) { console . log ( error . response . data . status ); } } In the above function, the type of…

Jest : custom matcher for exceptions

As of now jest matcher toThrow help us to match only the Exception class or the error message. If we want to do any matching against the custom details on the error instance, we have to use try...catch and assign the error to a variable and do expect manually like below let err : ValidationError ; try { await validatorDto ( /* params */ ); } catch ( error ) { err = error ; } expect ( err . details…

Reviewdog : configure reviewdog for eslint using github actions

To make the eslint issues more visible on pull requests, especially the warnings, we used to add comments on PR as part of our review process. This manual process is error-prone and slows down our review process. To make it streamlined, I was looking for a tool which can report the eslint errors/warnings as PR review annotations on the exact line where eslint finds the problems. Thus I came to…

JavaScript : String.length is not the count of characters

In JavaScript, String.length does not represent the count of characters. Rather they represent the count of codepoints. Since the normal characters can be represented using single codepoints, in most cases we get String.length is the same as the count of characters. But as we start using unicode characters , which uses more than one codepoint to represent a single character, we start getting wrong…

GitHub action to deploy review apps to surge

This post explains a simple GitHub action to deploy your frontend app to surge for each pull request created. This post assumes you already have surge installed and logged in. Now, let’s generate a new surge token surge token Add the generated token to Github secrets so that GitHub actions can use it. Next, add the following action into .github/workflows . # .github/workflows/surge.yml name :…

Alfred : workflow to simulate keyboard input

Some web applications, especially certain banking applications won’t allow you to copay and paste the text into input forms. In such cases, you might need to enter the text manually or find some way to simulate the keyboard text input. Using the Alfred app, you can add a custom workflow to simulate text input. This blog explains how you can create a custom workflow. 1. Create a new workflow You…

Rails: custom param name for member resource

By default, the param name for the member resources like :show , :update , :delete etc are id . Occasionally we come into a situation where the name id doesn’t make sense to the routes. For example, in reservations we have :show but instead of id we will be passing confirmation_code instead of reservation id. Using params[:id] in this case will be confusing for the people who read the code. This…

Using SSL in local development

The first step to using SSL on local development is to generate a self-signed certificate on our development machine. If you are familiar with openssl , you can use it to generate the certificate. But it’s kinda tricky to get valid certificates. The easiest way is to use mkcert to generate self-signed certificates Install & setup mkcert On the mac, we can use Homebrew to install it. brew install…

Migrating database from one to another

Recently I came into a situation where I want to migrate one database to another. Once from sqlite to PostgreSQL & another from MariaDB (MySQL) to PostgreSQL. Both were not production level apps. Taking a database dump and importing it into others won’t work because of data type issues & various syntax errors. The only way it worked for me is by using the sequel gem. It will work in just 2…

Auto deploy to heroku using Gitlab CI

As of now, Heroku doesn’t support auto-deploy from GitLab. So we have to use Gitlab CI to deploy to Heroku. This post will help you to set up auto deploy to Heroku. For this blog post, we will take a rails app with a Postgres database. We need Gitlab to run the unit tests and deploy to staging and then later to production. For staging and production, we will keep different branches to make things…

ReactJS : designing better component api (Functional)

Part 1 of this post is available at designing better component api - UI Part 2 : For Functional / Large UI components In part 1 we discussed the API for primitive UI components. In this we will discuss about Functional (not stateless) components or some large UI components composed using primitive UI components. Derive value from existing data Refrain yourself from passing unwanted props, where…

ReactJS : designing better component api (UI)

A good api has a huge impact on the productivity of the team and stability of the product. The secret to designing a good component api is the mix of splitting the components to smaller components passing minimal data to the components deduce the data from existing data instead of having a separate state. have similar api for similar components Keep it futuristic and extendable For this post, we…

ReactJS : beginner mistakes and how to avoid them

1. Not splitting into components Most people start writing the component and forget to split. So team will endup with very huge render method. Some try to abstract it into instance methods. My rule of thump here is, If you are adding instance method for partial render, mostly it can be splitted into smaller components. 2. component name starts with small letter. React has a rule that component…

ReactJS : simple HTML5 Validation

Please note this blog post drafted long back and might be outdated. please notify me if you see any issues. When I get question like which validation package you use in ReactJS, I usually answer saying I don’t use any. I go with HTML5 validation which native to browsers for simple validation and rest of them do it on server side. In my case it served well enough for all my projects.May be your…

ReactJS : lazy loading large libraries

We tend to use different external libraries for various purposes. The size of those libraries varies from small/medium/large. What happens when you want to use a large library only for a particular route? It doesn’t make any sense to load that library along with the initial bundle or with the vendor. Such large libraries are needed only when a user navigates to that particular route. This blog…

Android : Different application id for debug and production

Last couple of months in my free time I was working on a small Android app by learning react native. This is my first experience of developing apps for mobiles. When I started one thing I wanted to set up in the initial stage itself was the different application id for debug and production apks. This will help me have both builds installed at the same time. Also, it will make sure the even while…

Install wireguard on FireTV

WireGuard is a moden next gen VPN which utilizes cryptography. Since Wireguard is not available on FireTV’s app store, we have to sideload the app using adb. Enable ADB on FireTV. First step to side load the app to FireTv is to enable ADB debugging and Apps from unknown sources . To do this Goto Settings -> My FireTV -> Developer Options Choose Option My FireTV from Settings Choose Developer…

Owning the content

Photo by Kelli McClintock on Unsplash. I started this blog 10 years back on Blogspot. Now there are even more platforms available to host your blogs. The negative effect of using those platforms for the easiness and engagement is, we as a user is losing control over our content. Internet is made up of hyperlinks. The hyperlinks going dead is not a good sign for a healthy internet. The platforms…

Being a responsible product dev

There are a lot of ways you can be a responsible developer. By responsibility, most devs will think of shipping on time with minimum bugs and compliant with business needs etc. when devs get blinded with responsibility towards business needs, they forget / forced to forget their responsibility towards users. Let me try to list down some major issues I have seen when I use different products. To…

The danger of personalised feed

Most of the social apps now come with features called personalised feed or personalised experience . They claim that they will provide personalised experience to each user differently as per their interest and people always buy it. unsplash-logo William White Why the apps are giving you personalised feeds? Because That’s where they are taking control of the things what you see or what you read.…

In search of a height adjustable standing desk

I was searching for a height adjustable standing desk for my personal use. I searched online and went to some store and local vendors to see the demo. What are the features I was looking for? Electric/motor based Table Top 5 feet x 2.5 feet Preset memory (Good to have, not mandatory) Flipper box with cable management (not mandatory) What were the options available? Feather lite Feather lite is the…

Git: send patch using send-email & Gmail

Github revolutionized how we contribute to Open Source. All my past contribution was through Github pull requests. As a break from that recently I got a opportunity to contribute a minor patch to wireguard-android which is outside of github ecosystem. Since wireguard follows linux way of accepting patches via email I have to setup the git send-email command to send my patch. This post is about my…

ELM : Fetching data with XHR

This post will explain how to use elm/http package to fetch data using XHR requests in ELM applications. Since the reponse is from the outer world of ELM we need to decode JSON response before ELM can consume it. For the purpose of demo we will fetch posts from jsonplaceholder and render the list of titles from its /posts resource. Setup Model Lets start with defining model for the application.…

Setting up dangerjs

Ever felt like you are repeating the same comment over and over in many PR’s during the code review? Then this post is for you. Even though this can’t be avoided 100%, you can automate some of these by offloading to dangerjs . Introduction If you never heard about dangerjs before, it’s a small tool which can run tasks against the changed files in a PR and add comment the problems. Comments can be…

Jest : why we stopped snapshot tests

When jest introduced snapshot tests we were very eager to try out. we were using snapshot for most of the components and soon enough we have to make a decision that we no longer do snapshot tests. The main reason for such a decision was 1. Test failure due to external dependencies. Our tests started failing due to changes in external dependencies. The external ui component updated the css class…