<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/rss.xsl" type="text/xsl"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>aburduzha.dev</title><description>Personal website by Anton Burduzha — a senior software engineer sharing deep dives into web development</description><link>https://aburduzha.dev</link><item><title>Why localStorage Still Crashes Your Website in 2023</title><link>https://aburduzha.dev/posts/localstorage-crash</link><guid isPermaLink="true">https://aburduzha.dev/posts/localstorage-crash</guid><description>The localStorage errors we hit after moving from Create React App to Next.js, from SSR ReferenceErrors to SecurityErrors in the browser, and how we fixed them.</description><pubDate>Sat, 28 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In autumn 2022, I decided to migrate one of our work projects from the Create React App to NextJs. The goal of this was to increase the performance of a few pages, separate pages for mobile devices from the main app, and decrease the number of 3rd parties with access. Most of our goals were achieved successfully but according to our Airbrake notifier, localStorage was always breaking something. I hadn’t previously considered that localStorge would be a challenge, as I had been storing users’ phone numbers and i18n keys there and couldn&apos;t use a backend API instead.&lt;/p&gt;
&lt;p&gt;So, I needed localStorage to work since it was the only option for me.&lt;/p&gt;
&lt;h2&gt;My challenges&lt;/h2&gt;
&lt;p&gt;One problem I faced was an error at compile time.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ReferenceError: localStorage is not defined
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yeah, I was definitely a newbie to NextJs and totally missed the fact that my pages perform server render first and foremost. Meaning that &lt;code&gt;window&lt;/code&gt; and &lt;code&gt;localStorage&lt;/code&gt; wouldn&apos;t be accessible until the page is loaded on the client’s side.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useEffect } from &apos;react&apos;;

useEffect(() =&amp;gt; {
  const phoneNumber = localStorage.getItem(&apos;phoneNumber&apos;);
}, []);

// and
const onChange = (value) =&amp;gt; localStorage.setItem(&apos;phoneNumber&apos;, value);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The solution was quite simple, to put everything related to it into useEffect and onChange handlers to make sure it reflects in the browser.&lt;/p&gt;
&lt;p&gt;The second and the third were my biggest problems because I managed to solve them only after reading lots of articles, posts, and documentation pages.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SecurityError: The operation is insecure.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We received this error only from the Safari browser, so I decided to dig a little further. I found an interesting fact. If all cookies in privacy and security settings are blocked by the user, every time your website calls either &lt;code&gt;localStorage&lt;/code&gt; or &lt;code&gt;sessionStorage&lt;/code&gt; it will cause an error.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Even calling
console.log(localStorage);
// or
localStorage?.getItem(&apos;phoneNumber&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wrapping everything in &lt;code&gt;try...catch&lt;/code&gt; wasn’t a good option because it would increase the existing codebase, which is bad practice. Following the code snippet on &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API?ref=hackernoon.com#feature-detecting_localstorage&quot;&gt;MDN&lt;/a&gt;, I decided to write a utility class that would cover all vital components related to the &lt;code&gt;localStorage&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AppStorage {
  getItem(key) {
    if (this.storageAvailable()) {
      return window.localStorage?.getItem(key);
    }
    return undefined;
  }

  setItem(key, value) {
    if (this.storageAvailable()) {
      window.localStorage?.setItem(key, value);
    }
  }

  storageAvailable(type = &apos;localStorage&apos;) {
    let storage;
    try {
      storage = window[type];
      const x = &apos;__storage_test__&apos;;
      storage.setItem(x, x);
      storage.removeItem(x);
      return true;
    } catch (e) {
      return (
        e instanceof DOMException &amp;amp;&amp;amp;
        // everything except Firefox
        (e.code === 22 ||
          // Firefox
          e.code === 1014 ||
          // test name field too, because code might not be present
          // everything except Firefox
          e.name === &apos;QuotaExceededError&apos; ||
          // Firefox
          e.name === &apos;NS_ERROR_DOM_QUOTA_REACHED&apos;) &amp;amp;&amp;amp;
        // acknowledge QuotaExceededError only if there&apos;s something already stored
        storage &amp;amp;&amp;amp;
        storage.length !== 0
      );
    }
  }
}
// and inside our components
const phoneNumber = AppStorage.getItem(&apos;phoneNumber&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks quite elegant, doesn’t it?&lt;/p&gt;
&lt;p&gt;We have this utility class in a separate file and can use it across the app by applying the &lt;a href=&quot;https://en.wikipedia.org/wiki/Don%27t_repeat_yourself&quot;&gt;DRY&lt;/a&gt; strategy. By the way, this utility class also helped to solve the last problem:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TypeError: Cannot read properties of null (reading &apos;setItem&apos;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Airbrake sent us that error from Android on new versions of Chrome. I still haven’t figured out what caused it, because the operator &lt;code&gt;.?&lt;/code&gt; didn&apos;t help, &lt;code&gt;window.localStorage&lt;/code&gt; was defined. But it was &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I really hope it will be fixed in the nearest months or years and Browser API will be unified across all browsers. Yes, I’m a dreamer. And of course, I believe this article and my experience will help someone who is struggling with &lt;code&gt;localStorage&lt;/code&gt; crashes.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Building Embeddable Widgets with TypeScript</title><link>https://aburduzha.dev/posts/js-embeddable-widget</link><guid isPermaLink="true">https://aburduzha.dev/posts/js-embeddable-widget</guid><description>How I built a lightweight embeddable widget for B2B customers with TypeScript, web components and Shadow DOM.</description><pubDate>Mon, 30 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Sometimes, along with the main product, there is the need to create embeddable lightweight widgets, that your b2b customers can add to their website to show notifications, ads, quick chat functionality, etc.&lt;/p&gt;
&lt;p&gt;In this blog post, I will show how I implemented it for our product. You will have a ready-to-insert script that will download and run the bundle file. The main requirement for our widget is the minimum number of technologies to use. I chose web components and a Shadow DOM for this project.&lt;/p&gt;
&lt;h2&gt;What is Shadow DOM?&lt;/h2&gt;
&lt;p&gt;To cut a long story short, I would say that the Shadow DOM is a DOM with elements and styles that have their own scope. It is not affected by the main CSS of the website because it’s encapsulated. You can’t access the Shadow DOM elements with querySelector or other APIs and you don’t need to think about CSS collisions. Fantastic no?&lt;/p&gt;
&lt;p&gt;You might think iframes are the most popular form of scoped DOMs and it’s better to use them, but iframes have their own disadvantages, such as cors, and responsiveness.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Shadow DOM pros&lt;/th&gt;
&lt;th&gt;Shadow DOM cons&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Scoped DOM&lt;/td&gt;
&lt;td&gt;Compatibility&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Scoped CSS&lt;/td&gt;
&lt;td&gt;Using multiple Shadow DOM projectscan cause conflict with each other&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Composition&lt;/td&gt;
&lt;td&gt;Accessibility&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Performance&lt;/td&gt;
&lt;td&gt;Custom fonts&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;blockquote&gt;
&lt;p&gt;Just FYI, I’m going to include code snippets with explanations for each step, so that we can “code along” and figure it out bit by bit.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Also at the top of each snippet, you will find the name of the file, so you’re not confused about where to put it. But be careful not to copy it with the code, as it will cause an error for some extensions.&lt;/p&gt;
&lt;h2&gt;Setting up our project&lt;/h2&gt;
&lt;p&gt;Let’s start building our project by creating a folder called ”whatever name you like”. Please open a shell and execute&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then install our first dependencies. I hope you are already familiar with &lt;code&gt;webpack&lt;/code&gt; and know its purpose. Along with it, we&apos;re going to install Typescript for type checking and reducing the number of errors.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save-dev webpack webpack-cli webpack-dev-server typescript ts-loader html-webpack-plugin cross-env
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If everything is fine, let’s create a file in the root of our directory with the name tsconfig.json and the next config inside. It&apos;s just simple instruction, which explains to Typescript how to read our code. Nothing advanced. You can read about each line &lt;a href=&quot;https://basarat.gitbook.io/typescript/project/compilation-context/tsconfig&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;src&quot;,
    &quot;rootDir&quot;: &quot;.&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;target&quot;: &quot;es2015&quot;,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;lib&quot;: [&quot;esnext&quot;, &quot;es2017&quot;, &quot;ES2015&quot;, &quot;dom&quot;],
    &quot;sourceMap&quot;: true,
    &quot;declaration&quot;: false,
    &quot;declarationMap&quot;: false,
    &quot;noImplicitAny&quot;: true,
    &quot;strict&quot;: true,
    &quot;strictNullChecks&quot;: true,
    &quot;strictBindCallApply&quot;: true,
    &quot;strictFunctionTypes&quot;: true,
    &quot;typeRoots&quot;: [&quot;node_modules/@types&quot;],
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true
  },
  &quot;include&quot;: [&quot;src/**/*&quot;]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next important part of our setup is configuring &lt;code&gt;webpack&lt;/code&gt; to compile all our stuff. Please create the file called &lt;code&gt;webpack.config.js&lt;/code&gt; in the root of the project directory. It comes with simple instructions for bundlers to transform our code into plain JS, CSS, etc.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const path = require(&apos;path&apos;);
const webpack = require(&apos;webpack&apos;);
const HTMLWebpackPlugin = require(&apos;html-webpack-plugin&apos;);

module.exports = {
  entry: {
    Widget: &apos;./src/index.ts&apos;,
  },
  mode: &apos;development&apos;,
  output: {
    library: &apos;Widget&apos;,
    libraryTarget: &apos;umd&apos;,
    libraryExport: &apos;default&apos;,
    path: path.resolve(__dirname, &apos;dist&apos;),
    filename: `widget.js`,
  },
  resolve: {
    extensions: [&apos;.ts&apos;, &apos;.js&apos;, &apos;.scss&apos;],
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [{ loader: &apos;ts-loader&apos; }],
      },
    ],
  },
  plugins: [
    new HTMLWebpackPlugin({ template: path.resolve(__dirname, &apos;index.html&apos;) }),
    new webpack.HotModuleReplacementPlugin(),
  ],
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To end up our setup - create basic &lt;code&gt;index.html&lt;/code&gt; and &lt;code&gt;index.ts&lt;/code&gt; files in the root as previous files and put the next code inside to check if everything works properly.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;console.log(1);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset=&quot;UTF-8&quot; /&amp;gt;
    &amp;lt;title&amp;gt;Widget&amp;lt;/title&amp;gt;
    &amp;lt;meta
      name=&quot;viewport&quot;
      content=&quot;width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0&quot;
    /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you see the result of &lt;code&gt;console.log&lt;/code&gt; in the browser, it appears that everything is functioning properly.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./image.png&quot; alt=&quot;Sentry issue&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The setup is finished. Congrats, finally we can start our development.&lt;/p&gt;
&lt;h2&gt;Development step&lt;/h2&gt;
&lt;p&gt;We can create custom HTML elements, described by our class, with their own methods and properties, events, and so on. There are two kinds of custom elements:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Autonomous custom elements&lt;/strong&gt; – “all-new” elements, extending the abstract &lt;code&gt;HTMLElement&lt;/code&gt; class.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Customized built-in elements&lt;/strong&gt; – extending built-in elements, like a customized button, based on &lt;code&gt;HTMLButtonElement&lt;/code&gt; etc.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this tutorial, we need autonomous elements. To create a custom element, we need to tell the browser several details about it: how to show it, what to do when the element is added or removed from the page, etc. This is done by creating a class with special methods, which is easy to do, as there are only a few methods, and all of them are optional.&lt;/p&gt;
&lt;p&gt;A browser calls the method &lt;code&gt;connectedCallback&lt;/code&gt; when the element is added to the document. At that moment we create the &lt;code&gt;template&lt;/code&gt; element and put our markup inside with &lt;code&gt;innerHTML&lt;/code&gt; property. A built-in &lt;code&gt;template&lt;/code&gt; element serves as storage for HTML markup templates. The browser ignores its contents and only checks for syntax validity, but we can access and use it in JavaScript to create other elements. &lt;code&gt;this.shadowDocument&lt;/code&gt; is a document fragment that is attached to the main element.&lt;/p&gt;
&lt;p&gt;To create a Shadow DOM for an element, we call &lt;code&gt;this.attachShadow()&lt;/code&gt;. The next snippet gives you more understanding of what element we attach to the &lt;code&gt;template.content&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export const WidgetElement = () =&amp;gt; {
  class WidgetElement extends HTMLElement {
    constructor() {
      super();
      this.shadowDocument = this.attachShadow({ mode: &apos;open&apos; });
    }

    private shadowDocument: ShadowRoot;

    connectedCallback(): void {
      const template = document.createElement(&apos;template&apos;);
      template.innerHTML = &apos;&amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;&apos;;
      this.shadowDocument?.appendChild(template.content.cloneNode(true));
    }
  }

  return WidgetElement;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please remove &lt;code&gt;console.log&lt;/code&gt; from the &lt;code&gt;index.ts&lt;/code&gt; file and simply copy and paste the code below. Our next step is defining the custom web component and its custom element. Let it be &lt;code&gt;&amp;lt;custom-widget&amp;gt;&amp;lt;/custom-widget&amp;gt;&lt;/code&gt;. We create an element &lt;code&gt;custom-widget&lt;/code&gt; that is going to be our root and attach WidgetElement (&lt;code&gt;template&lt;/code&gt; content) to it.&lt;/p&gt;
&lt;p&gt;Below, we invoke our code and show the new tag by appending it to the end of the body of the website.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { WidgetElement } from &apos;./WidgetElement&apos;;

const App = (() =&amp;gt; {
  const scriptEl = document.getElementById(&apos;top-widget&apos;);
  if (scriptEl) {
    if (!customElements.get(&apos;custom-widget&apos;)) {
      customElements.define(&apos;custom-widget&apos;, WidgetElement());
    }

    const componentInstance = document.createElement(&apos;custom-widget&apos;, {
      is: &apos;custom-widget&apos;,
    });

    const container = document.body;
    container.appendChild(componentInstance);
  }
})();

export default App;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Simply put the script below to &lt;code&gt;index.html&lt;/code&gt; instead of the tag &lt;code&gt;&amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script id=&quot;top-widget&quot;&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result will be the same, see the picture below, but using the custom web component created with the Shadow DOM.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./image-2.png&quot; alt=&quot;Sentry issue&quot; /&gt;&lt;/p&gt;
&lt;p&gt;We’ve mentioned one of the Shadow DOM advantages before - Scoped CSS. I spent a fair amount of time to decide the best way to style web components and realized that there were none. As always, it depends on your experience, knowledge, stack, etc. All we really need is to find a way to get CSS and deliver inside &lt;code&gt;style&lt;/code&gt; tags at the top of our root.&lt;/p&gt;
&lt;p&gt;I&apos;m going to show my option, which in my personal opinion isn&apos;t bad at all. Please install the next dependencies and let&apos;s apply them one by one.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save-dev css-loader node-sass sass-loader sass-to-string
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Reading and transforming Sass to CSS, &lt;code&gt;webpack&lt;/code&gt; requires adding the following loaders. &lt;code&gt;sass-to-string&lt;/code&gt; is required to take styles and use them as a plain string. You will see how Sass will be imported and inserted into the template.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// add those options under ts-loader config
{
    test: /\.scss$/,
    exclude: /node_modules/,
    use: [
        &apos;sass-to-string&apos;,
        {
            loader: &apos;sass-loader&apos;,
            options: {
                sassOptions: {
                    outputStyle: &apos;compressed&apos;,
                },
            },
        },
    ],
},
{
    test: /\.css$/,
    use: [&apos;css-loader&apos;],
},
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we’re creating a new directory called &lt;code&gt;styles&lt;/code&gt; with &lt;code&gt;main.scss&lt;/code&gt; file inside. Just copy and paste the example inside. You&apos;ll easily change styles later, or forget, play with them whichever way you want.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.widget {
  width: 240px;
  height: 80px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  p {
    margin: 0;
    color: gray;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To prevent the mixing of logic in one file, let’s create a new one with the name &lt;code&gt;widget.template.ts&lt;/code&gt; and add a new markup with predefined CSS classes to it. Previously we explained &lt;code&gt;webpack&lt;/code&gt; what to do with Sass in our project, so just import the &lt;code&gt;main.scss&lt;/code&gt;example code at the top of the file. Don&apos;t forget to add the new declaration to the new globals.d.ts file in the root of &lt;code&gt;src&lt;/code&gt; directory for &lt;code&gt;.scss&lt;/code&gt; files.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import styles from &apos;./styles/main.scss&apos;;

const renderTemplate = () =&amp;gt; {
  return `
            &amp;lt;style&amp;gt;${styles}&amp;lt;/style&amp;gt;
            &amp;lt;div class=&quot;widget&quot;&amp;gt;
                &amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
        `;
};

export { renderTemplate };
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;declare module &apos;*.scss&apos; {
  export default {};
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At the end of this part, we import the template and substitute an old plain string &lt;code&gt;p&lt;/code&gt; tag with it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// add import at the top of the file
import { renderTemplate } from &apos;./widget.template&apos;;

// update existing method
private appendShadowDOMWithData = (): void =&amp;gt; {
    const template = document.createElement(&apos;template&apos;);
    template.innerHTML = renderTemplate();
    this.shadowDocument?.appendChild(template.content.cloneNode(true));
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;During this step, we already have an idea about the style of our future widget. Let’s add some icons inside our component. It’s hard to imagine any widget without awesome icons or pictures. I suggest adding some to our widget as well, just in case you will be struggling with it. I found a simple star SVG image.&lt;/p&gt;
&lt;p&gt;Put your valid SVG icon into a new folder &lt;code&gt;assets/[name-of-your-svg].svg&lt;/code&gt; and import it inside our &lt;code&gt;widget.template.ts&lt;/code&gt; file. Don&apos;t forget to tell &lt;code&gt;webpack&lt;/code&gt; to recognize it and add new instructions to &lt;code&gt;globals.d.ts&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// add this option under css-loader config
{
    test: /\.(png|svg|jpg|jpeg|gif)$/i,
    type: &apos;asset/resource&apos;,
},
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import star from &apos;./assets/star.svg&apos;;

// and below
&amp;lt;div class=&quot;widget&quot;&amp;gt;
    &amp;lt;img src=&quot;${star}&quot; alt=&quot;star&quot; /&amp;gt;
    &amp;lt;p&amp;gt;Hello world&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;declare module &apos;*.svg&apos; {
  export default {};
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step is changing our font. To be honest, I didn’t find any information on how to add fonts inside of the Shadow DOM project and apply them. But there is still access to Google fonts. I created a script that allows us to download the necessary font. We use Rubik as the main font in our product, so let’s take it here as well.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const FONT_FACE = `@import url(&apos;https://fonts.googleapis.com/css2?family=Rubik:wght@400;500&amp;amp;display=swap&apos;);`;

export const setupFontFaces = () =&amp;gt; {
  if (document.querySelector(&apos;style[data-description=&quot;font-faces&quot;]&apos;)) {
    return;
  }
  const style = document.createElement(&apos;style&apos;);
  style.dataset.description = &apos;font-faces&apos;;

  style.appendChild(document.createTextNode(FONT_FACE));
  document.head.appendChild(style);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the snippet above we create &lt;code&gt;style&lt;/code&gt; element in the outer scope and import google Fonts via the link. Nothing special, I tested it several times and it didn&apos;t make any collisions with the main website. The next step is to call our &lt;code&gt;setupFontFaces&lt;/code&gt; function during the initialization of the widget.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { setupFontFaces } from &apos;./setupFonts&apos;;

// and add inside our constructor
constructor() {
    super();
    setupFontFaces();
    this.shadowDocument = this.attachShadow({ mode: &apos;open&apos; });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you open the network tab in the browser web tools, you’ll see that Rubik web font was downloaded.&lt;/p&gt;
&lt;p&gt;And here we are!&lt;/p&gt;
&lt;p&gt;Just add it either globally or to a specific selector.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;body {
  font-family: &apos;Rubik&apos;;
}
p {
  margin: 0;
  font-family: &apos;Rubik&apos;;
  color: gray;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All that is left is to add &lt;code&gt;position: absolute;&lt;/code&gt; and position styles to our element to make it look like a real widget. The last and main part is building our project. Run &lt;code&gt;npm run build&lt;/code&gt; and look inside the &lt;code&gt;dist&lt;/code&gt; folder. There is a file &lt;code&gt;Widget.min.js&lt;/code&gt;. Below there is an example of how another website can access your file. Just put it somewhere on the bucket or server and serve it under some URL.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script id=&quot;top-widget&quot; src=&quot;YOUR_BUCKET_URL/Widget.min.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great, we have finished this simple but cool project. Just imagine what interesting embeddable widgets you can build with the help of this example.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>How to Upload Source Maps to Sentry with Next.js</title><link>https://aburduzha.dev/posts/next-sentry-sourcemaps</link><guid isPermaLink="true">https://aburduzha.dev/posts/next-sentry-sourcemaps</guid><description>Two ways to get source maps uploaded to Sentry from a Next.js 12 project after migrating error monitoring from Airbrake.</description><pubDate>Mon, 06 Feb 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Nowadays every modern web application uses platforms that provide error monitoring in real-time. They have support for different languages and technologies. And that’s great because the quality of development grows every year.&lt;/p&gt;
&lt;p&gt;I’m a big fan of tools that help my team instantly react to bugs and crashes and fix them ASAP. It’s necessary when you are building a startup and trying to show your customers the best service. For instance, we used to monitor our frontend errors in &lt;code&gt;Airbrake&lt;/code&gt; and fixed repeated crashes for the mobile Safari browser. That was a big win because I had started to hate that issue (everyone faced that issue which cost him plenty of hours to find the solution). Recently, my team made the decision to migrate our front-end projects from &lt;code&gt;Airbrake&lt;/code&gt; to &lt;code&gt;Sentry&lt;/code&gt;. And like a big part of other developers, I was struggling with uploading source maps there.&lt;/p&gt;
&lt;p&gt;I think the following solutions can help those who have &lt;code&gt;~Next.js@12&lt;/code&gt; and &lt;code&gt;~@sentry/nextjs@7.3+&lt;/code&gt; versions on their projects.&lt;/p&gt;
&lt;h2&gt;Solution 1&lt;/h2&gt;
&lt;p&gt;If you see a notification similar to that in the picture below on an Issue page inside Sentry don’t fret. &lt;code&gt;@sentry/nextjs&lt;/code&gt; skipped the uploading of some source maps for Next.js generated files. In my case, those were errors that related to the framework/main files.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./image.png&quot; alt=&quot;Sentry issue&quot; /&gt;&lt;/p&gt;
&lt;p&gt;A little explanation: When Sentry is reacting to any error or event, it tries to get the source maps from the &lt;code&gt;release&lt;/code&gt; archive that it has uploaded. According to the GitHub issue conversation, the framework&apos;s code does not get uploaded by default anymore and Sentry doesn’t have access to all files for resolving stack trace.&lt;/p&gt;
&lt;p&gt;Take a look at this note from Sentry manual setup documentation:&lt;/p&gt;
&lt;p&gt;:::important
If you find that there are in-app frames in your client-side stack traces that aren&apos;t getting source-mapped even when most others are, it&apos;s likely because they are from files in &lt;code&gt;static/chunks/&lt;/code&gt; rather than &lt;code&gt;static/chunks/pages/&lt;/code&gt;. By default, such files aren&apos;t uploaded because the majority of the files in &lt;code&gt;static/chunks/&lt;/code&gt; only contain Next.js or third-party code, and are named in such a way that it&apos;s hard to distinguish between relevant files (ones containing your code) and irrelevant ones.
:::&lt;/p&gt;
&lt;p&gt;To make it upload everything, try to expand your current &lt;code&gt;next.config.js&lt;/code&gt; with the next properties.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;module.exports = withSentryConfig(
  {
    ...yourNextConfig,
    sentry: {
      widenClientFileUpload: true,
    },
  },
  {
    ...yourWebpackSentryConfig,
    ignore: [],
  },
  yourSentryConfig,
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It helped me to resolve 2 of the 3 errors that I got. For the majority, it’ll solve 100% of problems with source maps.&lt;/p&gt;
&lt;h2&gt;Solution 2&lt;/h2&gt;
&lt;p&gt;Let’s move on. The last problem was related to a square brackets notation for dynamic route values. If I catch an error on the client side(browser side), the stack trace paths are sent encoded but they’re not decoded when they reach the sentry server. Since the path is encoded and the string &lt;code&gt;%5Bslug%5D.js&lt;/code&gt; is not equal to &lt;code&gt;[slug].js&lt;/code&gt;, the source map is not matched/not found/whatever. When Sentry is sending the frames, it includes this encoded URL instead of the decoded URL.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I’ve found the solution in rewriting StackFrame.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Just follow the next instructions. Install &lt;code&gt;@sentry/integrations&lt;/code&gt; package to expand your current client config.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save @sentry/integrations
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import { RewriteFrames } from &apos;@sentry/integrations&apos;;

Sentry.init({
  ...yourSentryClientConfig,
  integrations: [
    ...yourSentryClientConfig.integrations,
    new RewriteFrames({
      iteratee: (frame) =&amp;gt; {
        frame.filename = frame.filename.replace(distDir, &apos;app:///_next&apos;);
        // here we are decoding our square brackets []
        frame.filename = decodeURI(frame.filename);
        return frame;
      },
    }),
  ],
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great! I hope this solves at least one person’s problems!&lt;/p&gt;
&lt;p&gt;As new technologies constantly evolve, their versions get mismatched and make many developers cry. But god bless a huge programmer community that is glad to share their experience with others.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Implementing i18n in Next.js: A Guide to Non-Route-Based Localization</title><link>https://aburduzha.dev/posts/next-non-route-i18n</link><guid isPermaLink="true">https://aburduzha.dev/posts/next-non-route-i18n</guid><description>How we moved a Next.js app to i18next with ni18n while keeping the language out of the URL, because the QR codes were already printed.</description><pubDate>Wed, 22 Feb 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Motivation&lt;/h2&gt;
&lt;p&gt;Recently, we migrated our sub-project from &lt;code&gt;react-localization&lt;/code&gt; to &lt;code&gt;i18next&lt;/code&gt;. During that migration, the main goal was to keep the previous behavior of setting and changing language in our app.&lt;/p&gt;
&lt;p&gt;Storing language in a route path is a commonly used practice for the Nextjs framework. But for our project, that was an inappropriate solution. Our main application allows businesses to generate QR codes for their customers with a link to the sub-application where the end user can leave feedback regarding service quality and satisfaction. All QR codes had already been printed, and new ones would cost a fortune for the business. The previous version of the sub-app used to be built on the base of CRA, and only half a year ago, it was migrated to Nextjs. So, we were looking for library or libraries which could provide us with non-route-based internationalization and API similar to &lt;code&gt;react-i18next&lt;/code&gt;. We found &lt;code&gt;ni18n&lt;/code&gt;. This is a library specifically designed for use with Nextjs. &lt;code&gt;ni18n&lt;/code&gt; provides a simple and flexible way to add i18n functionality to Nextjs projects, including support for server-side rendering and other advanced features.&lt;/p&gt;
&lt;h2&gt;Basic Setup&lt;/h2&gt;
&lt;p&gt;Let’s install all necessary dependencies to start working on our project.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install i18next react-i18next ni18n
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step is to expand the existing &lt;code&gt;next.config.js&lt;/code&gt; with the default i18n config.&lt;/p&gt;
&lt;p&gt;Basically, we need only a few fields for a quick start. &lt;code&gt;locales&lt;/code&gt; is required to show all the locales we want to support in the app, and &lt;code&gt;defaultLocale&lt;/code&gt; will be used when visiting a non-locale prefixed path (for us, it’s just the default language).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;module.exports = {
  ...yourNextConfig,
  i18n: {
    defaultLocale: &apos;GB&apos;,
    locales: [&apos;GB&apos;, &apos;UA&apos;, &apos;PT&apos;],
  },
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we are required to create a new file in the root or utils/plugins/etc. directory named &lt;code&gt;ni18n.config.js&lt;/code&gt;. &lt;code&gt;supportedLngs&lt;/code&gt; - names which show us supported languages, and &lt;code&gt;ns&lt;/code&gt; - namespaces, which we can use in some cases.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export const ni18nConfig = {
  supportedLngs: [&apos;GB&apos;, &apos;UA&apos;, &apos;PT&apos;],
  ns: [&apos;namespace-name&apos;],
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A few more things left. Our application requires &lt;code&gt;I18nextProvider&lt;/code&gt;, so let’s wrap the &lt;code&gt;App&lt;/code&gt; with the high-order component imported from &lt;code&gt;i18n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It will initialize the &lt;code&gt;i18nex&lt;/code&gt; instance and provide it as a context for all the children.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { appWithI18Next } from &apos;ni18n&apos;;
import { ni18nConfig } from &apos;../ni18n.config&apos;;

const App = ({ Component, pageProps }) =&amp;gt; &amp;lt;Component {...pageProps} /&amp;gt;;

export default appWithI18Next(App, ni18nConfig);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the last preparation step before we started using translation into our components is a filling of translation files. The important thing - keep the following file structure.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;└── locales
    ├── GB
    │   ├── namespace-name.json  // { &quot;key1&quot;: &quot;Test&quot; }
    │
    ├── UA
    │   ├── namespace-name.json  // { &quot;key1&quot;: &quot;Тест&quot; }
    │
    ├── PT
		    ├── namespace-name.json  // { &quot;key1&quot;: &quot;Teste&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we’ve done with the setup and are ready to start integration of the i18n feature into components. Let’s take a look at the example in &lt;code&gt;ComponentName.jsx&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We extract the &lt;code&gt;t&lt;/code&gt; function from &lt;code&gt;useTranslation&lt;/code&gt; hook which will return translated string for the selected language. Looks simple, doesn’t it?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useTranslation } from &apos;react-i18next&apos;;

export const MyComponent = () =&amp;gt; {
  const { t } = useTranslation();
  return &amp;lt;div&amp;gt;{t(&apos;key1&apos;)}&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you store user language in DB, don’t forget to create a context with &lt;code&gt;React.Context&lt;/code&gt; or any other solution to wrap pages and set the language in &lt;code&gt;useEffect&lt;/code&gt;. Below, I’ll show you a simple snippet of how it could be implemented.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const I18nProvider = ({ children, data }) =&amp;gt; {
  const { i18n } = useTranslation();

  const { language = &apos;GB&apos; } = data;

  useEffect(() =&amp;gt; {
    i18n.changeLanguage(language);
  }, [language]);

  return &amp;lt;I18nContext.Provider&amp;gt;{children}&amp;lt;/I18nContext.Provider&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s it. I hope it helped you to save some time, as always. In the future, we are going to migrate the existing i18n approach to route based. The reason is pretty simple - a unification of all our applications. I’ll definitely describe it in one of my next articles.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Next.js and SignalR: Effortless Socket Integration and Troubleshooting</title><link>https://aburduzha.dev/posts/next-signalr-issue</link><guid isPermaLink="true">https://aburduzha.dev/posts/next-signalr-issue</guid><description>Integrating @microsoft/signalr with Next.js and fixing the problems we ran into along the way.</description><pubDate>Wed, 06 Sep 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A minority, but still a massive number of projects, require web sockets integration to provide instant reaction of an interface on changes without re-fetching data.&lt;/p&gt;
&lt;p&gt;It’s an essential thing, and we are not going to talk about them or make a comparison between 3rd-party libraries that provide API for a better dev experience.&lt;/p&gt;
&lt;p&gt;My goal is to show how to integrate quickly &lt;code&gt;@microsoft/signalr&lt;/code&gt; with NextJs. And how to solve the problems we faced during development.&lt;/p&gt;
&lt;p&gt;I hope everyone has already installed and deployed the NextJS project locally. In my case, the version is &lt;code&gt;13.2.4&lt;/code&gt;. Let’s add some more important libraries: &lt;code&gt;swr&lt;/code&gt; (version &lt;code&gt;2.1.5&lt;/code&gt;) for data fetching and further work with the local cache and &lt;code&gt;@microsoft/signalr&lt;/code&gt; (version &lt;code&gt;7.0.5&lt;/code&gt;) - API for web sockets.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --save @microsoft/signalr swr
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s start with creating a simple fetcher function and a new hook called &lt;code&gt;useChatData&lt;/code&gt; to get initial data from our REST API. It returns a list of the messages for the chat, fields that detect errors and loading state, and the method &lt;code&gt;mutate&lt;/code&gt; that allows to change cached data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import useSWR from &apos;swr&apos;;

type Message = {
  content: string;
  createdAt: Date;
  id: string;
};

async function fetcher&amp;lt;TResponse&amp;gt;(url: string, config: RequestInit): Promise&amp;lt;TResponse&amp;gt; {
  const response = await fetch(url, config);
  if (!response.ok) {
    throw response;
  }
  return await response.json();
}

export const useChatData = () =&amp;gt; {
  const { data, error, isLoading, mutate } = useSWR&amp;lt;Message[]&amp;gt;(&apos;OUR_API_URL&apos;, fetcher);
  return {
    data: data || [],
    isLoading,
    isError: error,
    mutate,
  };
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To test that it works as it is supposed, let’s update our page component. Import our hook at the top, and extract data from it like in the snippet below. If it works, you will see rendered data. As you see, it’s quite simple.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useChatData } from &apos;hooks/useChatData&apos;;

const Chat: NextPage = () =&amp;gt; {
	const { data } = useChatData();

	return (
		&amp;lt;div&amp;gt;
            {data.map(item =&amp;gt; (
                &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
             ))}
        &amp;lt;/div&amp;gt;
	);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step requires connecting our future page to web sockets, catching &lt;code&gt;NewMessage&lt;/code&gt; events, and updating a cache with a new message. I propose to start with building the socket service in a separate file.&lt;/p&gt;
&lt;p&gt;According to the examples in SignalR docs, we have to create an instance of connection for further listening to events. I also added a connections object for preventing duplicates and two helpers to start/stop the connections.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { HubConnection, HubConnectionBuilder, LogLevel } from &apos;@microsoft/signalr&apos;;

let connections = {} as {
  [key: string]: { type: string; connection: HubConnection; started: boolean };
};

function createConnection(messageType: string) {
  const connectionObj = connections[messageType];
  if (!connectionObj) {
    console.log(&apos;SOCKET: Registering on server events &apos;, messageType);
    const connection = new HubConnectionBuilder()
      .withUrl(&apos;API_URL&apos;, {
        logger: LogLevel.Information,
        withCredentials: false,
      })
      .withAutomaticReconnect()
      .build();

    connections[messageType] = {
      type: messageType,
      connection: connection,
      started: false,
    };
    return connection;
  } else {
    return connections[messageType].connection;
  }
}

function startConnection(messageType: string) {
  const connectionObj = connections[messageType];
  if (!connectionObj.started) {
    connectionObj.connection
      .start()
      .catch((err) =&amp;gt; console.error(&apos;SOCKET: &apos;, err.toString()));
    connectionObj.started = true;
  }
}

function stopConnection(messageType: string) {
  const connectionObj = connections[messageType];
  if (connectionObj) {
    console.log(&apos;SOCKET: Stoping connection &apos;, messageType);
    connectionObj.connection.stop();
    connectionObj.started = false;
  }
}

function registerOnServerEvents(
  messageType: string,
  callback: (payload: Message) =&amp;gt; void,
) {
  try {
    const connection = createConnection(messageType);
    connection.on(&apos;NewIncomingMessage&apos;, (payload: Message) =&amp;gt; {
      callback(payload);
    });
    connection.onclose(() =&amp;gt; stopConnection(messageType));
    startConnection(messageType);
  } catch (error) {
    console.error(&apos;SOCKET: &apos;, error);
  }
}

export const socketService = {
  registerOnServerEvents,
  stopConnection,
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So now, our page might look like in the code snippet. We fetch and extract &lt;code&gt;data&lt;/code&gt; with the list of messages and render them. Also, &lt;code&gt;useEffect&lt;/code&gt; above registers the &lt;code&gt;NewMessage&lt;/code&gt; event, creates a connection, and listens to the backend.&lt;/p&gt;
&lt;p&gt;When the event triggers, the &lt;code&gt;mutate&lt;/code&gt; method from the hook updates the existing list with a new object.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useChatData } from &apos;hooks/useChatData&apos;;
import { socketService } from &apos;api/socket&apos;;

const Chat: NextPage = () =&amp;gt; {
	const { data } = useChatData();

	useEffect(() =&amp;gt; {
        socketService.registerOnServerEvents(
            &apos;NewMessage&apos;,
            (payload: Message) =&amp;gt; {
                mutate(() =&amp;gt; [...data, payload], { revalidate: false });
            }
        );
    }, [data]);

	useEffect(() =&amp;gt; {
        return () =&amp;gt; {
            socketService.stopConnection(&apos;NewMessage&apos;);
        };
    }, []);

	return (
		&amp;lt;div&amp;gt;
            {data.map(item =&amp;gt; (
                &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
            ))}
        &amp;lt;/div&amp;gt;
	);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks good to me, it works, and we see how new messages appear in the feed. I chose the basic example with chat because it’s clear and easy to understand. And, of course, you apply it on your own logic.&lt;/p&gt;
&lt;h3&gt;Small Bonus&lt;/h3&gt;
&lt;p&gt;Using one of the versions (&lt;code&gt;@microsoft/signalr&lt;/code&gt;), we faced a problem with duplications. It was connected to &lt;code&gt;useEffect&lt;/code&gt;, the dependency array. Each time the dependency was changed, &lt;code&gt;connection.on(event, callback);&lt;/code&gt; cached callback and triggered it again and again.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  // data equals [] by default (registerOnServerEvents 1 run),
  // but after initial data fetching it changes (registerOnServerEvents 2 run)
  // each event changes data and triggers running of registerOnServerEvents
  socketService.registerOnServerEvents(
    &apos;NewMessage&apos;,
    // callback cached
    (payload: Message) =&amp;gt; {
      // mutate called multiple times on each data change
      mutate(() =&amp;gt; [...data, payload], { revalidate: false });
    },
  );
}, [data]);
// after getting 3 messages events, we had got 4 messages rendered lol
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The quickest and most reliable solution we found was keeping a copy of data inside the React &lt;code&gt;ref&lt;/code&gt; and using it inside &lt;code&gt;useEffect&lt;/code&gt; for future updates.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useChatData } from &apos;hooks/useChatData&apos;;
import { socketService } from &apos;api/socket&apos;;

const Chat: NextPage = () =&amp;gt; {
	const { data } = useChatData();
	const messagesRef = useRef&amp;lt;Message[]&amp;gt;([]);

	useEffect(() =&amp;gt; {
	     messagesRef.current = chatData;
    }, [chatData]);

	useEffect(() =&amp;gt; {
        socketService.registerOnServerEvents(
            &apos;NewMessage&apos;,
            (payload: Message) =&amp;gt; {
			    const messagesCopy = messagesRef.current.slice();
                mutate(() =&amp;gt; [...messagesCopy, payload], { revalidate: false });
            }
        );
    }, [data]);

	useEffect(() =&amp;gt; {
        return () =&amp;gt; {
            socketService.stopConnection(&apos;NewMessage&apos;);
        };
    }, []);

	return (
		&amp;lt;div&amp;gt;
            {data.map(item =&amp;gt; (
                &amp;lt;div key={item.id}&amp;gt;{item.content}&amp;lt;/div&amp;gt;
            ))}
        &amp;lt;/div&amp;gt;
	);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Currently, we use a new version of &lt;code&gt;@microsoft/signalr&lt;/code&gt; which it seems already has necessary fixes. But anyway, if someone finds this solution useful and uses this workaround, I will be happy. To conclude, I want to say that my experience with SignalR is quite positive, installation didn’t require any specific dependencies or settings, and it works fine and covers our needs.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>A/B Testing on the Frontend: Three Bugs That Broke Our Test</title><link>https://aburduzha.dev/posts/ab-testing-frontend-bugs</link><guid isPermaLink="true">https://aburduzha.dev/posts/ab-testing-frontend-bugs</guid><description>Three frontend bugs that made a broken A/B test look like a win, how I fix them in Next.js now, and a live demo where you can break a split yourself.</description><pubDate>Tue, 03 Nov 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;On one project, our A/B test said variant B won. It hadn&apos;t. The test was broken, and all three bugs that broke it lived in frontend code: how we picked a variant, when we logged that a user was in the test, and how the page was cached.&lt;/p&gt;
&lt;p&gt;This post goes through each bug, how it showed up, and how I handle it now in Next.js App Router. At the end there&apos;s the checklist I run before launching a test and a live demo where you can break a test on purpose and watch the check catch it.&lt;/p&gt;
&lt;h2&gt;The red flag: the split wasn&apos;t 50/50&lt;/h2&gt;
&lt;p&gt;You configure a test so half of the users see A and half see B. A hash spreads users between the groups, which is close enough to random. With 100,000 users you expect about 50,000 in each group. A small gap is normal, something like 50,200 and 49,800. Flip a fair coin 100,000 times and you won&apos;t get exactly 50/50 either, but you also won&apos;t get 53/47.&lt;/p&gt;
&lt;p&gt;If you do get 53,000 and 47,000, that isn&apos;t chance. Something in the code is losing or adding people in one group, and it&apos;s doing it for a specific reason. Say variant B throws an error on old Android phones before it sends its event. Group B now holds mostly people on newer, faster phones, who tend to buy more anyway. B &quot;wins&quot;, even though B is broken and the two groups stopped being comparable.&lt;/p&gt;
&lt;p&gt;This is called Sample Ratio Mismatch (SRM). A chi-square test answers the question &quot;could a gap this big be random?&quot;. If the answer is no, don&apos;t trust the results, however good they look. Go find the bug first.&lt;/p&gt;
&lt;h2&gt;Bug 1: we logged assignment, not exposure&lt;/h2&gt;
&lt;p&gt;We sent the &quot;user is in the experiment&quot; event when the variant was assigned. The change itself was further down the page. Half the users counted in the test never scrolled to it, so they were measured without ever seeing the thing we were testing. That dilutes the effect. Worse, the share of people who never get there can differ between variants, and then the groups drift apart.&lt;/p&gt;
&lt;p&gt;The fix is to log an exposure when the user actually sees the change, and to do it in every group, control included. I wrap the changed block in the same component in all variants and log once when half of it is on screen:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const observer = new IntersectionObserver(
  ([entry]) =&amp;gt; {
    if (!entry?.isIntersecting) return;
    // threshold 0.5 alone never fires for a block taller than two screens
    const seen =
      entry.intersectionRatio &amp;gt;= 0.5 ||
      entry.intersectionRect.height &amp;gt;= window.innerHeight / 2;
    if (seen) {
      logExposureOnce(experiment, variant, isOverride);
      observer.disconnect();
    }
  },
  { threshold: Array.from({ length: 21 }, (_, i) =&amp;gt; i / 20) },
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The check for tall blocks matters. If one variant is a tall block, &lt;code&gt;threshold: 0.5&lt;/code&gt; can&apos;t fire on a normal screen, so the tall variant logs fewer exposures than the short one, and you&apos;re back to a broken split.&lt;/p&gt;
&lt;p&gt;The event goes out with &lt;code&gt;navigator.sendBeacon&lt;/code&gt; to a first-party endpoint (&lt;code&gt;/api/e&lt;/code&gt;). Ad blockers don&apos;t cut a first-party request, so whatever data you lose, you lose it the same way in every group. The endpoint takes the user ID from an &lt;code&gt;httpOnly&lt;/code&gt; cookie, never from the request body.&lt;/p&gt;
&lt;h2&gt;Bug 2: bucketing with Math.random()&lt;/h2&gt;
&lt;p&gt;The variant was picked with &lt;code&gt;Math.random()&lt;/code&gt;. Same user, next page load, different variant. One person ends up in both groups, and the group counts stop making sense.&lt;/p&gt;
&lt;p&gt;The variant has to be a pure function of the user and the experiment. I hash the experiment key together with the user ID and take the result modulo 100:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function assign&amp;lt;K extends ExperimentKey&amp;gt;(key: K, unitId: string) {
  const { variants, weights, rollout } = experiments[key];
  const control = variants[0] as VariantOf&amp;lt;K&amp;gt;;

  // Hash 1: is this user in the experiment at all?
  if (hash(`incl:${key}:${unitId}`) % 100 &amp;gt;= rollout) {
    return { variant: control, inExperiment: false };
  }

  // Hash 2: which variant
  const bucket = hash(`${key}:${unitId}`) % 100;
  let acc = 0;
  for (let i = 0; i &amp;lt; variants.length; i++) {
    acc += weights[i] ?? 0;
    if (bucket &amp;lt; acc) return { variant: variants[i] as VariantOf&amp;lt;K&amp;gt;, inExperiment: true };
  }
  return { variant: control, inExperiment: true };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The same user now gets the same variant on every request, on any server, with no stored state. Because the experiment key is part of the input, being in variant B of one test says nothing about which group you&apos;re in for another.&lt;/p&gt;
&lt;p&gt;There are two hashes on purpose. One decides whether a user is in the experiment at all, the other decides which variant. When you raise the rollout from 10% to 50%, new users join and nobody who was already in moves between groups. If one hash did both jobs, raising the rollout would reshuffle people and bias the results.&lt;/p&gt;
&lt;p&gt;The user ID itself comes from &lt;code&gt;proxy.ts&lt;/code&gt; (called &lt;code&gt;middleware.ts&lt;/code&gt; before Next.js 16). It sets a random &lt;code&gt;uid&lt;/code&gt; cookie on the first visit and passes it to Server Components as a request header, because a cookie set on the response isn&apos;t visible to the same request.&lt;/p&gt;
&lt;p&gt;:::note
Bots, users outside the rollout, and requests without an ID get control and log nothing. If they were counted, they could skew the split on their own.
:::&lt;/p&gt;
&lt;h2&gt;Bug 3: the CDN cached one variant&lt;/h2&gt;
&lt;p&gt;The page was cached at the CDN, and the variant wasn&apos;t part of the cache key. Whoever hit the page first decided what everyone else saw. Almost everyone gets the same variant, and the split ends up something like 90/10 instead of 50/50.&lt;/p&gt;
&lt;p&gt;My rule now: the server decides, the client only renders, and every variant is cached separately. For most pages the variant is picked in a Server Component and streamed inside &lt;code&gt;&amp;lt;Suspense&amp;gt;&lt;/code&gt;, while the rest of the page stays a static shell. There&apos;s no SDK in the browser and no anti-flicker snippet. The fallback is a placeholder with the same size, never one of the variants, so there&apos;s no layout shift and no flicker.&lt;/p&gt;
&lt;p&gt;For pages that should be fully static, like pricing, I run the same &lt;code&gt;decide()&lt;/code&gt; in &lt;code&gt;proxy.ts&lt;/code&gt; and rewrite to a prebuilt copy of the page:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (req.nextUrl.pathname === &apos;/pricing&apos;) {
  const d = decide(&apos;pricing-layout&apos;, {
    unitId: uid,
    isBot,
    overrides: parseOverrides(overrides),
  });
  res = NextResponse.rewrite(new URL(`/pricing/${d.variant}`, req.url), {
    request: { headers },
  });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each variant is built with &lt;code&gt;generateStaticParams&lt;/code&gt;. The browser URL stays &lt;code&gt;/pricing&lt;/code&gt;, and the CDN caches each &lt;code&gt;/pricing/&amp;lt;variant&amp;gt;&lt;/code&gt; as a separate page. Add &lt;code&gt;noindex&lt;/code&gt; and a canonical link to the variant routes so search engines don&apos;t index three copies of the same page.&lt;/p&gt;
&lt;h2&gt;The things around the bugs&lt;/h2&gt;
&lt;p&gt;A few smaller habits came out of this.&lt;/p&gt;
&lt;p&gt;Every experiment lives in one typed registry with its variants, weights, rollout, owner and expiry date. &lt;code&gt;variant === &apos;gren&apos;&lt;/code&gt; becomes a type error, and removing an experiment shows every place that still uses it. A small CI script fails the build when the weights don&apos;t add up to 100 or an experiment is past its expiry date, so old flags get removed instead of turning into dead code.&lt;/p&gt;
&lt;p&gt;QA can force a variant with &lt;code&gt;?exp=pricing-layout:cards&lt;/code&gt;. Those exposures are still logged, with &lt;code&gt;isOverride: true&lt;/code&gt;, so analysis can drop them.&lt;/p&gt;
&lt;p&gt;:::tip
This setup doesn&apos;t do statistics: sample size, sequential testing and the rest. Use GrowthBook, Statsig or PostHog for that. Their SDKs can sit behind the same &lt;code&gt;decide()&lt;/code&gt; signature, so product code doesn&apos;t change.
:::&lt;/p&gt;
&lt;h2&gt;Checklist before you launch an A/B test&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;[ ] One hypothesis and one primary metric, set before launch&lt;/li&gt;
&lt;li&gt;[ ] Same user always gets the same variant (hash the user ID)&lt;/li&gt;
&lt;li&gt;[ ] Variant chosen on the server or edge, so no flicker&lt;/li&gt;
&lt;li&gt;[ ] Exposure logged when the user sees the change, in both groups&lt;/li&gt;
&lt;li&gt;[ ] Variant is part of the cache key&lt;/li&gt;
&lt;li&gt;[ ] Web Vitals and errors tracked per variant&lt;/li&gt;
&lt;li&gt;[ ] Flag removed once the test is over&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;The demo&lt;/h2&gt;
&lt;p&gt;After writing about these bugs, I built a demo where you can break a test yourself and watch it get caught: &lt;a href=&quot;https://ab-testing-nextjs.vercel.app/&quot;&gt;ab-testing-nextjs.vercel.app&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Each bug from this post is fixed there:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;On the checkout page nothing is logged until half of the changed block is on screen. If you don&apos;t scroll, you&apos;re not counted. A tracker in the corner shows how much of the block you&apos;ve seen.&lt;/li&gt;
&lt;li&gt;The overview page shows your anonymous ID, your variant in each experiment, and the hash buckets that picked it. Reload as often as you like and it stays the same.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;/pricing&lt;/code&gt; is a fully static page. The proxy picks the variant and serves a prebuilt copy, and the URL doesn&apos;t change when you switch layouts.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;My favorite part is the traffic simulator. It sends 100,000 fake visitors through the same &lt;code&gt;decide()&lt;/code&gt; the app uses and runs a chi-square check on the result. Turn on &quot;Inject a bug&quot; and some users in one variant stop logging their exposure, like a new page that crashes before the event goes out. The split stops matching the weights and the check flags it as a sample ratio mismatch right away. It&apos;s the red flag from the start of this post, in a form you can click.&lt;/p&gt;
&lt;p&gt;It&apos;s Next.js 16 App Router with no A/B testing vendor. The code is on &lt;a href=&quot;https://github.com/AntonBurduzha/ab-testing-nextjs&quot;&gt;GitHub&lt;/a&gt;, and the smaller version of the same setup is in &lt;a href=&quot;https://gist.github.com/AntonBurduzha/e9c0a1535934a0925ce38e58d602c0c9&quot;&gt;this gist&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Further reading:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.microsoft.com/en-us/research/articles/diagnosing-sample-ratio-mismatch-in-a-b-testing/&quot;&gt;Diagnosing Sample Ratio Mismatch in A/B Testing&lt;/a&gt;, from Microsoft ExP, on why the split goes off and how to debug it&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://martinfowler.com/articles/feature-toggles.html&quot;&gt;Feature Toggles&lt;/a&gt; by Pete Hodgson, on experiment flags as code with expiry dates&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://flags-sdk.dev/docs/frameworks/next/precompute&quot;&gt;Precompute&lt;/a&gt; in the Flags SDK docs, on static A/B variants without flicker in Next.js&lt;/li&gt;
&lt;/ul&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>How I Build Mieru with Claude Code Agents</title><link>https://aburduzha.dev/posts/mieru-claude-code-workflow</link><guid isPermaLink="true">https://aburduzha.dev/posts/mieru-claude-code-workflow</guid><description>One /task command takes each Mieru task from a written spec to a single commit, with separate agents for tests, review and verification, and two gates I hold.</description><pubDate>Fri, 20 Nov 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Mieru is my side project: privacy-first web analytics for small sites, with a 1 KB tracking script, no cookies and one page of numbers. Under the hood it&apos;s a FastAPI ingest service, a Redis stream, a writer that moves events into ClickHouse, and the ops to run it all on one server. The code and docs are public at &lt;a href=&quot;https://github.com/AntonBurduzha/mieru&quot;&gt;github.com/AntonBurduzha/mieru&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Most of the code is written by Claude Code. Every task goes through one command, &lt;code&gt;/task&lt;/code&gt;, which takes it from a spec to a single commit. Separate agents write the tests, review the diff and verify the result. I keep two gates: I approve the spec before anything is built, and I test the result before anything is committed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./agent-flow.png&quot; alt=&quot;The Mieru agent workflow, from /task to merge&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The whole setup is checked in under &lt;code&gt;.claude/&lt;/code&gt;: the &lt;code&gt;/task&lt;/code&gt; skill with its spec template, three agent definitions (&lt;code&gt;test-writer&lt;/code&gt;, &lt;code&gt;reviewer&lt;/code&gt;, &lt;code&gt;verifier&lt;/code&gt;), two hooks and &lt;code&gt;settings.json&lt;/code&gt;. The process is written up for people in &lt;code&gt;docs/workflow.md&lt;/code&gt;, and nothing in it depends on Claude Code. The spec is the contract, and its commands are ordinary shell commands.&lt;/p&gt;
&lt;h2&gt;Run 1: the spec and gate 1&lt;/h2&gt;
&lt;p&gt;I start with &lt;code&gt;/task T07&lt;/code&gt;. Claude reads the task&apos;s roadmap row, the feature entries, the architecture docs the task touches, the conventions and the code it will change. Then it writes &lt;code&gt;docs/tasks/T07-&amp;lt;slug&amp;gt;.md&lt;/code&gt; from a template:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a goal in one or two sentences;&lt;/li&gt;
&lt;li&gt;scope, with an &quot;Out&quot; list that names the task that does the rest;&lt;/li&gt;
&lt;li&gt;the exact files it may change, docs included;&lt;/li&gt;
&lt;li&gt;interfaces with their real names;&lt;/li&gt;
&lt;li&gt;acceptance criteria, each ending in an &lt;code&gt;auto:&lt;/code&gt; command that fails when the criterion is broken, or &lt;code&gt;human:&lt;/code&gt; steps I can follow.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That last rule does most of the work. A vague criterion has no command to attach, so it shows up at gate 1, before any code exists.&lt;/p&gt;
&lt;p&gt;The run then asks me to approve, and I can edit the spec file while the question waits. My checklist: clear scope, specific allowed files, observable criteria, a proof of done that proves each criterion, and a size of about 300 changed lines for an agent task. Bigger tasks get split. On approval, Claude creates the branch, sets the status to &lt;code&gt;build&lt;/code&gt;, and commits the spec on its own.&lt;/p&gt;
&lt;h2&gt;Tests first, from a separate agent&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;test-writer&lt;/code&gt; agent writes at least one test per &lt;code&gt;auto:&lt;/code&gt; criterion. It may only write in the test folders, and only files the spec allows. Its instructions also say the tests must fail for the right reason: a failed assertion, or an import of a name the spec says will be created. A typo or a broken fixture is its own bug to fix.&lt;/p&gt;
&lt;p&gt;The main session then checks that &lt;code&gt;git status&lt;/code&gt; shows only test files besides the spec, and that every criterion has a test. Keeping this agent separate means the implementer can&apos;t quietly fit the tests to its own code. Tasks with nothing to test in Python, like shell or CI work, skip the step and the spec says why.&lt;/p&gt;
&lt;h2&gt;The build, then review in a fresh context&lt;/h2&gt;
&lt;p&gt;The main session writes the code inside the allowed files, runs lint, types and tests until they&apos;re green, and updates the docs the spec lists. If it needs a file outside the list, it stops and asks.&lt;/p&gt;
&lt;p&gt;Then the &lt;code&gt;reviewer&lt;/code&gt; reads the change. It starts with a fresh context, so it has none of the reasoning that produced the code, and its tools are &lt;code&gt;Read&lt;/code&gt;, &lt;code&gt;Grep&lt;/code&gt;, &lt;code&gt;Glob&lt;/code&gt; and &lt;code&gt;Bash&lt;/code&gt;, so it can&apos;t edit anything. It reviews &lt;code&gt;git diff main&lt;/code&gt; against the spec and the conventions in a fixed order: correctness, privacy, tenant isolation, security, reliability, conventions, tests, docs, scope.&lt;/p&gt;
&lt;p&gt;Some checks are specific to Mieru. No IP address, user agent or request body may reach logs, Redis or the databases, and every query on tenant data has to be scoped by &lt;code&gt;org_id&lt;/code&gt; or &lt;code&gt;site_id&lt;/code&gt;. A generic bug-finding review wouldn&apos;t know those rules, so I run Claude Code&apos;s &lt;code&gt;/code-review&lt;/code&gt; only as a second opinion.&lt;/p&gt;
&lt;p&gt;Each finding gets a severity, a &lt;code&gt;file:line&lt;/code&gt;, a concrete scenario and the smallest fix:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Must-fix: &amp;lt;n&amp;gt; · Should-fix: &amp;lt;n&amp;gt; · Nit: &amp;lt;n&amp;gt;

1. [must-fix] path/to/file.py:42: &amp;lt;what breaks, the scenario&amp;gt;. Fix: &amp;lt;smallest change&amp;gt;.
2. [should-fix] ...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;/task&lt;/code&gt; applies every must-fix and should-fix finding, runs the checks again, and leaves the nits to me (&lt;code&gt;/task T07 apply nit 2&lt;/code&gt;).&lt;/p&gt;
&lt;h2&gt;The verifier can&apos;t make a check pass&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;verifier&lt;/code&gt; is the second read-only agent. It runs the standard checks, every &lt;code&gt;auto:&lt;/code&gt; command, the proof of done and the feature checks from &lt;code&gt;docs/features.json&lt;/code&gt;. It also checks scope (every changed file is on the allowed list) and test integrity (no test removed, skipped or loosened without a written reason). It only counts a criterion as proven if it ran the command in that session and saw it pass.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;VERDICT: DONE | FAIL | NEED_HUMAN

| # | Criterion | How | Result | Evidence |
|---|-----------|-----|--------|----------|
| 1 | &amp;lt;short&amp;gt;   | auto | pass  | `&amp;lt;command&amp;gt;` exit 0: &quot;12 passed in 0.8s&quot; |
| 2 | &amp;lt;short&amp;gt;   | human | unconfirmed | needs the developer: &amp;lt;steps&amp;gt; |
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;On FAIL, the main session fixes the cause and verifies again. After three FAILs in a row it stops and shows me the report&apos;s &quot;To reach DONE&quot; list.&lt;/p&gt;
&lt;p&gt;NEED_HUMAN means nothing failed, but something needs a person: a server check, a GitHub setting, or a criterion too vague to run. In T04, the automated deploy, the agents ran shellcheck, actionlint and the scope check, and the verifier returned NEED_HUMAN for the criteria that needed the real server and the GitHub settings. I ran those and pasted the output into &lt;code&gt;/task&lt;/code&gt;. The last criterion was proven by the merge&apos;s own CI deploy.&lt;/p&gt;
&lt;p&gt;:::note
The reviewer and the verifier run on the same model that wrote the code, so they can share blind spots. What helps: the reviewer starts fresh and works against a written spec, the verifier trusts only commands it ran itself, and the two gates stay with me.
:::&lt;/p&gt;
&lt;h2&gt;The debug map and gate 2&lt;/h2&gt;
&lt;p&gt;Before handing over, Claude adds a &quot;Where to debug&quot; table to the spec: three to five places where the task&apos;s behaviour is decided, each with a &lt;code&gt;file:line&lt;/code&gt;, how to reach it and what to look at. The line numbers are checked against the code on disk. In T06, the ClickHouse schema task, one row points at &lt;code&gt;ch_migrate.py:72&lt;/code&gt;, where the migration runner decides which files are pending, and names the test to run under the debugger to get there.&lt;/p&gt;
&lt;p&gt;The status becomes &lt;code&gt;test&lt;/code&gt;. I read the whole diff in Cursor, run the &quot;Test it yourself&quot; steps, and step through the parts I want to understand. If something is wrong, &lt;code&gt;/task T07 &amp;lt;what&apos;s wrong&amp;gt;&lt;/code&gt; sends it back: Claude reproduces it in a test, fixes it, and runs the reviewer and verifier again.&lt;/p&gt;
&lt;h2&gt;Run 2: one commit, and I push&lt;/h2&gt;
&lt;p&gt;When it works, I run &lt;code&gt;/task T07&lt;/code&gt; again, which means &quot;I tested it and it works&quot;. It confirms the DONE verdict, flips &lt;code&gt;passes&lt;/code&gt; to &lt;code&gt;true&lt;/code&gt; in &lt;code&gt;features.json&lt;/code&gt; only for features whose check the verifier saw exit 0, sets the status to &lt;code&gt;done&lt;/code&gt;, makes the task&apos;s one commit and writes the PR description to &lt;code&gt;.git/pr-T07.md&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Claude never pushes. The project settings deny it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;deny&quot;: [
  &quot;Read(./.env)&quot;, &quot;Read(./**/.env)&quot;, &quot;Read(./**/*.pem)&quot;,
  &quot;Bash(git push)&quot;, &quot;Bash(git push *)&quot;, &quot;Bash(ssh *)&quot;, &quot;Bash(rm -rf *)&quot;
]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I push, CI runs lint, types and tests against real databases, and I merge.&lt;/p&gt;
&lt;p&gt;On top of the deny list, &lt;code&gt;protect.sh&lt;/code&gt; runs before every &lt;code&gt;Bash&lt;/code&gt;, &lt;code&gt;Edit&lt;/code&gt;, &lt;code&gt;Write&lt;/code&gt;, &lt;code&gt;Read&lt;/code&gt;, &lt;code&gt;Grep&lt;/code&gt; and &lt;code&gt;Glob&lt;/code&gt; call. It blocks &lt;code&gt;.env&lt;/code&gt; files, private keys, &lt;code&gt;DROP TABLE&lt;/code&gt;, deleting Docker volumes and &lt;code&gt;git reset --hard&lt;/code&gt;, whatever a prompt says. &lt;code&gt;format.sh&lt;/code&gt; formats every file Claude writes.&lt;/p&gt;
&lt;p&gt;:::tip
&lt;code&gt;protect.sh&lt;/code&gt; reads the whole command, so a commit message that mentions &lt;code&gt;.env&lt;/code&gt; trips it too. &lt;code&gt;/task&lt;/code&gt; writes commit messages to a file and commits with &lt;code&gt;git commit -F&lt;/code&gt;.
:::&lt;/p&gt;
&lt;h2&gt;State lives in the spec&lt;/h2&gt;
&lt;p&gt;Each task&apos;s status (&lt;code&gt;todo&lt;/code&gt;, &lt;code&gt;spec&lt;/code&gt;, &lt;code&gt;build&lt;/code&gt;, &lt;code&gt;test&lt;/code&gt;, &lt;code&gt;done&lt;/code&gt;) is kept in the spec&apos;s frontmatter and its roadmap row. &lt;code&gt;/task&lt;/code&gt; reads it and continues from there, so a run can stop mid-build and pick up the next day.&lt;/p&gt;
&lt;p&gt;Every task also leaves a record. The spec&apos;s Review section holds every verdict and finding, and what was done about each. T01 had 15 acceptance criteria, each ending in a command, and finished with 61 tests at 97% coverage, merged as PR #6.&lt;/p&gt;
&lt;p&gt;Between the two gates the loop runs without me, and my time goes into the spec and my own test. I haven&apos;t measured tokens per task yet. Some tasks also run in human mode: the pipeline, the data model, auth and infrastructure, the parts I need to explain and defend myself. There &lt;code&gt;/task&lt;/code&gt; writes me a tutorial instead of the code, then reviews and verifies what I wrote.&lt;/p&gt;
&lt;p&gt;The full workflow and the agent definitions are in &lt;a href=&quot;https://github.com/AntonBurduzha/mieru/blob/main/docs/workflow.md&quot;&gt;&lt;code&gt;docs/workflow.md&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Markdown Preview Fold: Folding Sections in the VS Code Markdown Preview</title><link>https://aburduzha.dev/posts/markdown-preview-fold</link><guid isPermaLink="true">https://aburduzha.dev/posts/markdown-preview-fold</guid><description>How I built my first VS Code extension, which folds heading sections in the built-in Markdown preview of VS Code, Cursor and other forks.</description><pubDate>Wed, 25 Nov 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I read a lot of Markdown in my editor: specs, READMEs, my own notes. In Obsidian I fold the sections I&apos;ve already read and keep open only the part I&apos;m working on. The Markdown preview in VS Code and Cursor can&apos;t do that, so a long document stays one long scroll.&lt;/p&gt;
&lt;p&gt;I wrote my first VS Code extension to fix it. Markdown Preview Fold puts a caret next to every heading in the built-in preview, and a click folds the section. I released 0.1.0 on November 25, 2026, and it&apos;s at 0.1.3 now.&lt;/p&gt;
&lt;h2&gt;What it does&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A caret appears on hover next to every heading that has something under it, and stays visible while the section is folded. A folded heading gets a &quot;…&quot; after its text.&lt;/li&gt;
&lt;li&gt;Subsections keep their own state. Fold &quot;Install&quot;, then fold and unfold &quot;Setup&quot; above it, and &quot;Install&quot; is still folded.&lt;/li&gt;
&lt;li&gt;The state survives edits, tab switches and editor restarts, separately for each file.&lt;/li&gt;
&lt;li&gt;Collapse All and Expand All are in the preview&apos;s title bar, in the Command Palette, and on &lt;code&gt;Cmd+K Cmd+0&lt;/code&gt; / &lt;code&gt;Cmd+K Cmd+J&lt;/code&gt; (&lt;code&gt;Ctrl&lt;/code&gt; on Windows and Linux). They only apply while the preview has focus, so in the text editor the same keys still fold code.&lt;/li&gt;
&lt;li&gt;Option+click (Alt+click on Windows and Linux) folds a section together with all its subsections.&lt;/li&gt;
&lt;li&gt;A link to a heading inside a folded section opens the sections above it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The caret is a real &lt;code&gt;&amp;lt;button&amp;gt;&lt;/code&gt;, so it works with the keyboard and screen readers. Colors come from your theme, high contrast themes included.&lt;/p&gt;
&lt;h2&gt;Why I didn&apos;t use an existing extension&lt;/h2&gt;
&lt;p&gt;Markdown Preview Enhanced and similar extensions replace the preview with their own. I wanted one feature added to the preview I already use, with its scroll sync, styles and settings.&lt;/p&gt;
&lt;p&gt;Cursor was the other question. It has its own WYSIWYG Markdown editor, but that editor lives in Cursor&apos;s workbench code, and extensions have no API to reach it. The built-in VS Code preview does accept scripts, styles and markdown-it plugins from other extensions. If I target that preview, one extension works in VS Code, Cursor, VSCodium and Windsurf. In Cursor you open it with &quot;Markdown: Open Preview to the Side&quot;.&lt;/p&gt;
&lt;h2&gt;Two runtimes that can&apos;t call each other&lt;/h2&gt;
&lt;p&gt;The extension plugs into the built-in Markdown extension through three contribution points:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;contributes&quot;: {
  &quot;markdown.markdownItPlugins&quot;: true,
  &quot;markdown.previewScripts&quot;: [&quot;./dist/preview.js&quot;],
  &quot;markdown.previewStyles&quot;: [&quot;./media/preview.css&quot;]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That code runs in two places. The extension host is a Node process with the &lt;code&gt;vscode&lt;/code&gt; API: commands, menus, key bindings. It sees the Markdown engine but not the preview page. The preview page is a browser page inside a webview, with the DOM and &lt;code&gt;localStorage&lt;/code&gt;. It can&apos;t import &lt;code&gt;vscode&lt;/code&gt;, and the built-in preview already holds the only &lt;code&gt;acquireVsCodeApi()&lt;/code&gt; handle, so the page can&apos;t message my extension either.&lt;/p&gt;
&lt;p&gt;The build keeps them apart with two esbuild bundles and two tsconfig projects: Node and &lt;code&gt;vscode&lt;/code&gt; types without the DOM, and the DOM without &lt;code&gt;vscode&lt;/code&gt;. Code in the wrong runtime doesn&apos;t compile.&lt;/p&gt;
&lt;h2&gt;The preview rewrites its DOM on every edit&lt;/h2&gt;
&lt;p&gt;This was my first surprise. The preview never reloads when you type. It renders new HTML in the extension host, posts it to the page and patches &lt;code&gt;.markdown-body&lt;/code&gt; with morphdom. Morphdom compares the DOM with the new HTML, and my classes and carets aren&apos;t in that HTML, so after each keystroke they were gone.&lt;/p&gt;
&lt;p&gt;The script keeps the fold state in memory, and &lt;code&gt;renderView&lt;/code&gt; is idempotent: run it any number of times on the same DOM and you get the same result. It runs on every &lt;code&gt;vscode.markdown.updateContent&lt;/code&gt; event, which the preview fires after each patch. The patch and my render happen in the same task, before the browser paints, so there&apos;s no flicker.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function renderView(view: PreviewView, collapsed: ReadonlySet&amp;lt;string&amp;gt;): void {
  view.elements.forEach((element, index) =&amp;gt; {
    setHidden(element, isHiddenBy(view.outline.owners[index], collapsed));
  });
  for (const section of view.outline.sections) {
    const heading = view.elements[section.blockIndex];
    if (heading) renderHeading(heading, section, collapsed.has(section.key));
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To survive edits, a section needs a key that doesn&apos;t depend on its position. Line numbers change with every edit, and the preview&apos;s heading ids are slugs with numeric suffixes that shift across the document. So a key comes from the heading path: the parent&apos;s key, the heading text, and the index of that text among its siblings, for example &lt;code&gt;Guide#0 › Setup#0&lt;/code&gt;. Editing content keeps every key. Renaming a heading resets that section, and the README lists it as a known limitation.&lt;/p&gt;
&lt;p&gt;There was one more case. When the page loads from scratch (you open the preview or switch back to its tab), the preview&apos;s own script adds &lt;code&gt;.markdown-body&lt;/code&gt; after &lt;code&gt;DOMContentLoaded&lt;/code&gt; and fires no update event. Both scripts load with &lt;code&gt;async&lt;/code&gt;, so either can run first. I noticed it in Cursor: after a tab switch, the carets didn&apos;t show up until the next edit. Now a &lt;code&gt;MutationObserver&lt;/code&gt; waits for &lt;code&gt;.markdown-body&lt;/code&gt; and disconnects on the first update.&lt;/p&gt;
&lt;h2&gt;Talking to a page you don&apos;t own&lt;/h2&gt;
&lt;p&gt;Collapse All is a VS Code command, so it runs in the extension host, which has no channel to the page. The only thing the host can get onto the page is the HTML it helps render.&lt;/p&gt;
&lt;p&gt;So a markdown-it plugin adds a hidden marker to every render with the document URI and the pending command. The hard part was finding where to hook in. The engine caches parsed tokens per document version and passes &lt;code&gt;env.currentDocument&lt;/code&gt; only to &lt;code&gt;renderer.render&lt;/code&gt;. A core rule would see neither the document nor a new command. I found that by reading the built-in extension&apos;s code, and the plugin wraps &lt;code&gt;renderer.render&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function markerPlugin(md: MarkdownIt, options: MarkerOptions): void {
  const render = md.renderer.render.bind(md.renderer);
  md.renderer.render = (tokens, renderOptions, env: RenderEnv | undefined) =&amp;gt; {
    const html = render(tokens, renderOptions, env);
    const doc = env?.currentDocument;
    if (!doc) return html;
    return markerHtml(md, doc.toString(), options.getCommand()) + html;
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When you run Collapse All, the command stores &lt;code&gt;collapseAll:&amp;lt;uuid&amp;gt;&lt;/code&gt; for 1.5 seconds and calls &lt;code&gt;markdown.preview.refresh&lt;/code&gt;. The refresh is forced, so the preview sets the webview&apos;s HTML again, the page reloads, and the marker in the new HTML carries the command. The script applies each command id once.&lt;/p&gt;
&lt;p&gt;My first version got this wrong. It ignored a command on a page&apos;s first update, because I assumed the refresh would post &lt;code&gt;updateContent&lt;/code&gt; to the existing page. It reloads the page instead, so every bulk command was dropped. I found out by reading the &lt;code&gt;markdown-language-features&lt;/code&gt; extension bundled with Cursor.&lt;/p&gt;
&lt;p&gt;The host can&apos;t tell which preview has focus, so Collapse All and Expand All act on every open preview.&lt;/p&gt;
&lt;h2&gt;State that survives restarts&lt;/h2&gt;
&lt;p&gt;The webview &lt;code&gt;setState&lt;/code&gt; API belongs to the built-in preview, so it wasn&apos;t available to me. Then I learned that the workbench gives each webview type a stable origin, so the preview&apos;s &lt;code&gt;localStorage&lt;/code&gt; persists across tab switches and restarts. The extension keeps one versioned entry, keyed by file URI, with the 200 most recently changed files. Every access is wrapped in &lt;code&gt;try/catch&lt;/code&gt;, so in a sandbox without storage folding still works for the session.&lt;/p&gt;
&lt;p&gt;:::note
Hidden elements have empty boxes, which confuses the preview&apos;s scroll sync. &lt;code&gt;renderView&lt;/code&gt; removes the &lt;code&gt;code-line&lt;/code&gt; class from hidden blocks and puts it back when they show again.
:::&lt;/p&gt;
&lt;h2&gt;Testing and shipping&lt;/h2&gt;
&lt;p&gt;There are 65 unit and DOM tests in Vitest for the outline, keys, reducer and DOM code. Some of them run the whole script against a stand-in preview that updates with real morphdom. Four integration tests run in a real VS Code through &lt;code&gt;@vscode/test-cli&lt;/code&gt;. CI runs on Linux, macOS and Windows against VS Code 1.90 and stable.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;.vsix&lt;/code&gt; is around 16 KB, and &lt;code&gt;preview.js&lt;/code&gt; is 5.6 KB minified. A git tag publishes to Open VSX and GitHub Releases.&lt;/p&gt;
&lt;p&gt;I wanted the Marketplace in the same workflow, with Trusted Publishing (OIDC) and no stored token. The token exchange returned &lt;code&gt;401&lt;/code&gt;. GitHub repositories created after 2026-07-15 get immutable subject claims, and the most likely cause is that the Marketplace doesn&apos;t match that format yet. A personal access token would need an Azure DevOps organization, and a new one needs an Azure subscription. For now I upload the same CI-built &lt;code&gt;.vsix&lt;/code&gt; to the Marketplace by hand. ADR 010 in &lt;code&gt;docs/decisions.md&lt;/code&gt; has the details.&lt;/p&gt;
&lt;h2&gt;Install&lt;/h2&gt;
&lt;p&gt;Install it from the Extensions view or the links below, then open a Markdown file and run &lt;strong&gt;Markdown: Open Preview to the Side&lt;/strong&gt; (&lt;code&gt;Cmd+K V&lt;/code&gt; on macOS, &lt;code&gt;Ctrl+K V&lt;/code&gt; on Windows and Linux).&lt;/p&gt;
&lt;p&gt;:::tip
Cursor&apos;s inline Markdown editor won&apos;t show the carets. Use the classic preview from the command above.
:::&lt;/p&gt;
&lt;p&gt;The extension has no telemetry, makes no network requests, and never touches your files. It&apos;s MIT licensed.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://marketplace.visualstudio.com/items?itemName=antonburduzha.markdown-preview-fold&quot;&gt;VS Code Marketplace&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://open-vsx.org/extension/antonburduzha/markdown-preview-fold&quot;&gt;Open VSX&lt;/a&gt;, for Cursor, VSCodium and Windsurf&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/AntonBurduzha/markdown-preview-fold&quot;&gt;Source code on GitHub&lt;/a&gt;, with &lt;a href=&quot;https://github.com/AntonBurduzha/markdown-preview-fold/blob/main/docs/architecture.md&quot;&gt;how it works&lt;/a&gt; and &lt;a href=&quot;https://github.com/AntonBurduzha/markdown-preview-fold/blob/main/docs/decisions.md&quot;&gt;why it works this way&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you find a bug or have an idea, open an issue.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>A Plugin Slots Dashboard for Installation Limitter</title><link>https://aburduzha.dev/posts/installation-limitter-dashboard</link><guid isPermaLink="true">https://aburduzha.dev/posts/installation-limitter-dashboard</guid><description>I added a dashboard to Installation Limitter, an Obsidian plugin by Arthur Kh that makes you earn plugin slots by writing notes.</description><pubDate>Fri, 27 Nov 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Obsidian has a plugin for almost everything, and that&apos;s the trap. An evening of installing and tuning plugins feels productive, and at the end of it you haven&apos;t written a single note.&lt;/p&gt;
&lt;p&gt;Installation Limitter is a small plugin by Arthur Kh that makes you earn your plugins. I didn&apos;t write it. I found it, liked the idea, and added the part I missed: a dashboard in its settings that shows where you stand. Arthur merged my pull request on November 27, 2026, the dashboard shipped in 1.0.5, and the current version is 1.0.6.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./screenshots.png&quot; alt=&quot;Four screenshots of the dashboard and the blocked Browse button: free slots, every slot used, over the limit, and Limit reached!&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;How the limit works&lt;/h2&gt;
&lt;p&gt;You start with 5 plugin slots and get one more for every 10 files in your vault:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;limit = 5 + Math.floor(files / 10);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every file counts, attachments too. The plugin checks once a second. When you&apos;re at or over the limit, the &lt;strong&gt;Browse&lt;/strong&gt; button in &lt;strong&gt;Settings → Community plugins&lt;/strong&gt; turns into a disabled &lt;strong&gt;Limit reached!&lt;/strong&gt; button, and &lt;strong&gt;Install&lt;/strong&gt; in the plugin browser is disabled.&lt;/p&gt;
&lt;p&gt;Disabled plugins count. They stay installed in &lt;code&gt;.obsidian/plugins&lt;/code&gt;, so they still take a slot. The limit counts what you&apos;ve installed, whether it runs or not.&lt;/p&gt;
&lt;p&gt;You can also end up over the limit. That happens when you delete notes, or when you installed plugins before turning Installation Limitter on.&lt;/p&gt;
&lt;h2&gt;What was missing&lt;/h2&gt;
&lt;p&gt;The block worked, but it was the only feedback the plugin gave. You hit &lt;strong&gt;Limit reached!&lt;/strong&gt; and had no idea how far away the next slot was. And since disabled plugins take a slot, you could switch a plugin off to make room, see nothing change, and get no hint why.&lt;/p&gt;
&lt;p&gt;My pull request adds a dashboard to &lt;strong&gt;Settings → Installation Limitter&lt;/strong&gt; with three things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Slots used out of slots earned. A pill says &quot;4 free&quot;, &quot;Full&quot; or &quot;2 over&quot; in green, yellow or red. The bar under it stays in the theme&apos;s accent color while you have free slots and turns yellow or red after that.&lt;/li&gt;
&lt;li&gt;Progress toward the next slot, for example &quot;5 / 10 files&quot;, with its own bar.&lt;/li&gt;
&lt;li&gt;Installed plugins, split into &quot;Enabled&quot; and &quot;Disabled, still taking a slot&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The same PR fixes two install steps in the README (the Releases link and the plugin folder name), adds the screenshots, and attaches &lt;code&gt;styles.css&lt;/code&gt; to releases. Version 1.0.4 shipped without that file, and the dashboard needs it.&lt;/p&gt;
&lt;h2&gt;The math in one place&lt;/h2&gt;
&lt;p&gt;Before the dashboard, the limit was computed inline next to the button-blocking code. I moved it into &lt;code&gt;quota.ts&lt;/code&gt;, so the blocking check and the dashboard read the same numbers:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function getQuota(app: App): Quota {
  const filesCount = app.vault.getFiles().length;
  // Counts all installed community plugins, including disabled ones
  const pluginsCount = Object.keys(getManifests(app)).length;
  const limit = BASE_LIMIT + Math.floor(filesCount / FILES_PER_SLOT);
  const remaining = limit - pluginsCount;
  const nextSlotProgress = filesCount % FILES_PER_SLOT;
  const limitReached = pluginsCount &amp;gt;= limit;
  // Installing needs limit &amp;gt; pluginsCount, i.e. pluginsCount + 1 - BASE_LIMIT earned slots
  const filesToInstall = limitReached
    ? (pluginsCount + 1 - BASE_LIMIT) * FILES_PER_SLOT - filesCount
    : 0;
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;filesToInstall&lt;/code&gt; is the &quot;Write N more files&quot; line. To install one more plugin you need &lt;code&gt;pluginsCount + 1&lt;/code&gt; slots, which means &lt;code&gt;pluginsCount + 1 - 5&lt;/code&gt; earned slots, at 10 files each. With 9 plugins and 23 files that&apos;s &lt;code&gt;(9 + 1 - 5) × 10 - 23 = 27&lt;/code&gt;, the number in the red screenshot. With 42 files it&apos;s 8, the yellow one.&lt;/p&gt;
&lt;h2&gt;Obsidian 1.13 caches settings tabs&lt;/h2&gt;
&lt;p&gt;Since Obsidian 1.13, a plugin can describe its settings tab with &lt;code&gt;getSettingDefinitions()&lt;/code&gt;. Obsidian builds those definitions once, when the tab is added, and shows that cached copy every time you open the tab until you call &lt;code&gt;update()&lt;/code&gt;. That works for a list of toggles. A dashboard has to change whenever you add a file or install a plugin.&lt;/p&gt;
&lt;p&gt;Calling &lt;code&gt;update()&lt;/code&gt; every second would rebuild the tab for nothing. So the tab remembers what it was built from: the file count and the sorted plugin list, with a &lt;code&gt;+&lt;/code&gt; or &lt;code&gt;-&lt;/code&gt; for enabled state. The once-a-second check that already existed now also compares that key and calls &lt;code&gt;update()&lt;/code&gt; only when it changed. An open tab re-renders live.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;refreshIfChanged(quota: Quota): void {
	// Older versions call display() on every open, so they&apos;re always fresh
	if (!requireApiVersion(&apos;1.13.0&apos;)) {
		return;
	}
	if (dashboardKey(this.app, quota) !== this.builtFrom) {
		this.update();
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Older Obsidian versions use &lt;code&gt;display()&lt;/code&gt;, and the plugin&apos;s &lt;code&gt;minAppVersion&lt;/code&gt; is still 1.2.3, so both paths stay. They render the same rows from &lt;code&gt;dashboard.ts&lt;/code&gt;: each row is a name, an optional description, and an optional &lt;code&gt;render(setting)&lt;/code&gt; function.&lt;/p&gt;
&lt;h2&gt;Render runs again on the same row&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;update()&lt;/code&gt; keeps the rendered rows and calls &lt;code&gt;render&lt;/code&gt; on them again. A helper that only appends would leave two pills and two progress bars after the first refresh. So each helper first removes what an earlier render added:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function removeOwn(parent: HTMLElement, cls: string) {
  parent.querySelector(`:scope &amp;gt; .${cls}`)?.remove();
}

function addPill(setting: Setting, text: string, tone: PillTone) {
  removeOwn(setting.nameEl, &apos;plugins-limitter-pill&apos;);
  setting.nameEl.createSpan({ cls: [&apos;plugins-limitter-pill&apos;, `mod-${tone}`], text });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The plugin chips follow the same rule, and they live in &lt;code&gt;infoEl&lt;/code&gt; outside &lt;code&gt;descEl&lt;/code&gt;, so a &lt;code&gt;setDesc&lt;/code&gt; call can&apos;t wipe them.&lt;/p&gt;
&lt;p&gt;:::note
The dashboard rows put nothing in &lt;code&gt;controlEl&lt;/code&gt;, the right-hand column where a setting&apos;s toggle or button would go. Obsidian hides an empty control column, so the info column with the bar or the chips spans the whole row.
:::&lt;/p&gt;
&lt;h2&gt;Real screenshots&lt;/h2&gt;
&lt;p&gt;I wanted the README to show real states. I ran a second Obsidian with its own profile and a demo vault and drove it over the Chrome DevTools Protocol. A script created notes to move the dashboard between the red, yellow and green states. The fourth screenshot is the blocked &lt;strong&gt;Browse&lt;/strong&gt; button.&lt;/p&gt;
&lt;p&gt;I tested the PR on macOS with light and dark themes, in English and Ukrainian. I haven&apos;t tested it on mobile. The new strings went into every locale file the plugin ships.&lt;/p&gt;
&lt;h2&gt;Install&lt;/h2&gt;
&lt;p&gt;In Obsidian, open &lt;strong&gt;Settings → Community plugins → Browse&lt;/strong&gt; and search for &quot;Installation Limitter&quot;. The listing notes that the plugin hasn&apos;t been manually reviewed by Obsidian staff. After you enable it, open &lt;strong&gt;Settings → Installation Limitter&lt;/strong&gt; to see the dashboard.&lt;/p&gt;
&lt;p&gt;:::tip
You can earn slots by creating empty notes, or turn the plugin off. It&apos;s a nudge, and you can get around it. What it does is make installing a plugin a decision you think about for a second. I have 4 installed.
:::&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/mainarthur/obsidian-plugins-limitter&quot;&gt;Installation Limitter on GitHub&lt;/a&gt;, by Arthur Kh&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/mainarthur/obsidian-plugins-limitter/pull/2&quot;&gt;My pull request with the dashboard&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Thanks to Arthur for the plugin and for merging the PR.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>Restarting Every Container Under Traffic: Mieru&apos;s Deploy Drill</title><link>https://aburduzha.dev/posts/mieru-deploy-drill</link><guid isPermaLink="true">https://aburduzha.dev/posts/mieru-deploy-drill</guid><description>A bash drill sends page views while every app container of Mieru restarts, then counts what reached ClickHouse, including two runs I broke on purpose.</description><pubDate>Mon, 30 Nov 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;m building Mieru, privacy-first web analytics for small sites: a 1 KB script, no cookies, one dashboard page. The backend runs on one server with Docker Compose. Caddy terminates TLS in front of two ingest replicas, ingest writes events to a Redis stream, a writer moves them into ClickHouse, and a worker and an API sit next to them. The code is public at &lt;a href=&quot;https://github.com/AntonBurduzha/mieru&quot;&gt;github.com/AntonBurduzha/mieru&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Events lost during a deploy are easy to miss in an analytics product. Nothing errors, and the numbers just come out a little low. The architecture doc said a deploy loses nothing, and I wanted that measured. So task T15 added a drill: a bash script that restarts every app container while it sends traffic, then counts what came out the other end.&lt;/p&gt;
&lt;h2&gt;The deploy being tested&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;ops/deploy.sh&lt;/code&gt; restarts the app containers one at a time, each ready before the next:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;writer&lt;/code&gt;, then &lt;code&gt;worker&lt;/code&gt;, so the stream&apos;s reader is new before any new ingest writes to it;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ingest-1&lt;/code&gt;, then a wait for its &lt;code&gt;/health/ready&lt;/code&gt; plus 10 seconds;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ingest-2&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;api&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Caddy, Redis, Postgres and ClickHouse keep running. The &lt;code&gt;api&lt;/code&gt; has one replica, so the dashboard is unavailable for a few seconds while it restarts. Ingest has two, so one can take events while the other restarts.&lt;/p&gt;
&lt;p&gt;The drill runs from my Mac with &lt;code&gt;ops/drills/deploy-under-traffic.sh&lt;/code&gt;. Against the server it runs the real &lt;code&gt;deploy.sh&lt;/code&gt; over SSH. With &lt;code&gt;--local&lt;/code&gt; it targets the production Compose stack rehearsed on my Mac, with Caddy&apos;s local certificates, and replays the same restart order without git or migrations.&lt;/p&gt;
&lt;h2&gt;What &quot;under traffic&quot; means&lt;/h2&gt;
&lt;p&gt;Each event is one &lt;code&gt;curl&lt;/code&gt; to ingest&apos;s public URL, as a page view with its own path:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/drill/&amp;lt;run&amp;gt;/&amp;lt;n&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;run&amp;gt;&lt;/code&gt; is a UTC timestamp plus the drill&apos;s PID, and &lt;code&gt;&amp;lt;n&amp;gt;&lt;/code&gt; counts up from 1. The events go to a site of their own, &lt;code&gt;deploy-drill.invalid&lt;/code&gt; (&lt;code&gt;.invalid&lt;/code&gt; is a reserved domain), so they never mix with a real site&apos;s data. Each request carries a desktop Chrome user agent, because ingest drops curl&apos;s own user agent as a bot.&lt;/p&gt;
&lt;p&gt;The sender starts one background curl every &lt;code&gt;1/rate&lt;/code&gt; seconds. The default rate is 20 a second, and in practice it gets about 17, since every event is its own process. Each curl appends one line to &lt;code&gt;sent.log&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;seq&amp;gt; &amp;lt;second it started&amp;gt; &amp;lt;status&amp;gt; &amp;lt;curl exit code&amp;gt; &amp;lt;x-mieru-dropped&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The traffic starts 5 seconds before the deploy and keeps going 5 seconds after it returns. Since every line has the second it started, and the deploy&apos;s own log uses the same clock, the report can say how many events went out during the deploy.&lt;/p&gt;
&lt;p&gt;Before any of that, a preflight finds or creates the drill site, and sends a probe event every 3 seconds until ingest accepts one. That proves the URL, TLS, the bot filter and the site all work before the real run starts.&lt;/p&gt;
&lt;h2&gt;How events are counted&lt;/h2&gt;
&lt;p&gt;After the traffic stops, the drill polls ClickHouse every 2 seconds, for up to 90 seconds, until there is a row for every event ingest accepted:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;count_stored() {
  ch --param_site=&quot;$SITE&quot; --param_prefix=&quot;$PREFIX&quot; &amp;lt;&amp;lt;&apos;SQL&apos;
SELECT count(), uniqExact(pathname)
FROM mieru.events
WHERE site_id = {site:UInt32} AND startsWith(pathname, {prefix:String})
SQL
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A run passes only when four numbers match: events sent, events answered &lt;code&gt;202&lt;/code&gt; with no &lt;code&gt;X-Mieru-Dropped&lt;/code&gt; header, &lt;code&gt;count()&lt;/code&gt; and &lt;code&gt;uniqExact(pathname)&lt;/code&gt;. If &lt;code&gt;count()&lt;/code&gt; is lower, events were lost. Since every event has its own path, if &lt;code&gt;uniqExact(pathname)&lt;/code&gt; is lower than &lt;code&gt;count()&lt;/code&gt;, something was stored twice. On a mismatch, the drill lists the first 20 missing and duplicated paths, plus the stream&apos;s &lt;code&gt;XLEN&lt;/code&gt; and pending count.&lt;/p&gt;
&lt;p&gt;Exit code 0 is a pass and 1 is a loss. Exit 2 means the drill couldn&apos;t run at all: bad arguments, a missing tool, SSH, the probe, a failed deploy, or a ClickHouse it couldn&apos;t read. I didn&apos;t want a broken drill to look like a lost event.&lt;/p&gt;
&lt;h2&gt;The passing local run&lt;/h2&gt;
&lt;p&gt;On 2026-11-30 I ran it against the rehearsed stack on my Mac. One of the passing runs:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;events sent      748, 595 of them during the deploy (34s)
answered 202     748
stored           748 rows, 748 distinct paths
PASS: all 748 events were answered 202 and stored exactly once
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Three things in the design kept those 595 events safe while their containers restarted.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The writer restart.&lt;/strong&gt; While the writer is down, events wait in the Redis stream. On SIGTERM the writer finishes and acknowledges its current batch, and the new writer reads whatever is still pending first. It acknowledges a batch only after the insert into ClickHouse, and the insert carries a dedup token built from the batch&apos;s stream ids:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;async def insert_rows(client: AsyncClient, rows: Sequence[EventRow], *, token: str) -&amp;gt; None:
  &quot;&quot;&quot;Insert the rows as one block. ClickHouse skips a block whose token it already stored.&quot;&quot;&quot;
  data = [[getattr(row, column) for column in COLUMNS] for row in rows]
  await client.insert(
    TABLE, data, column_names=COLUMNS, settings={&quot;insert_deduplication_token&quot;: token}
  )
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So a batch retried after a crash isn&apos;t stored twice.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Caddy&apos;s retries.&lt;/strong&gt; Caddy health-checks both ingest replicas and retries a request that can&apos;t connect on the other one:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# comments and shared settings left out
reverse_proxy ingest-1:8001 ingest-2:8001 {
	lb_policy round_robin
	lb_try_duration 5s
	lb_try_interval 100ms
	fail_duration 5s
	health_uri /health
	health_interval 2s
	health_timeout 1s
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;The pause between replicas.&lt;/strong&gt; The 10 seconds after &lt;code&gt;ingest-1&lt;/code&gt; comes back is longer than &lt;code&gt;fail_duration&lt;/code&gt; (5 s) plus one health interval (2 s), so Caddy has &lt;code&gt;ingest-1&lt;/code&gt; back in rotation before &lt;code&gt;ingest-2&lt;/code&gt; goes down.&lt;/p&gt;
&lt;h2&gt;Breaking it on purpose&lt;/h2&gt;
&lt;p&gt;I had never seen the check fail, so a pass by itself didn&apos;t prove much. With &lt;code&gt;--local&lt;/code&gt;, the &lt;code&gt;DRILL_DEPLOY_CMD&lt;/code&gt; variable replaces the rolling restart with any command, and the spec&apos;s acceptance criteria used it to break the deploy twice:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;p=&apos;docker compose -f compose.prod.yaml --env-file ops/rehearsal.env&apos;
DRILL_DEPLOY_CMD=&quot;$p stop ingest-1 ingest-2 &amp;amp;&amp;amp; sleep 8 &amp;amp;&amp;amp; $p start ingest-1 ingest-2&quot; \
  ops/drills/deploy-under-traffic.sh --local
DRILL_DEPLOY_CMD=&quot;$p stop writer &amp;amp;&amp;amp; sleep 5 &amp;amp;&amp;amp; $p exec -T redis redis-cli XTRIM events MAXLEN 0 &amp;amp;&amp;amp; $p start writer&quot; \
  ops/drills/deploy-under-traffic.sh --local
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Both ingest replicas stopped for 8 seconds.&lt;/strong&gt; 334 sent, 216 answered &lt;code&gt;202&lt;/code&gt;, 118 failed: 116 with &lt;code&gt;503&lt;/code&gt; and 2 with &lt;code&gt;502&lt;/code&gt;. Exit 1. With no replica up, Caddy keeps retrying for its 5 seconds, then gives up with a 503.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The writer stopped and the stream trimmed.&lt;/strong&gt; &lt;code&gt;XTRIM events MAXLEN 0&lt;/code&gt; empties the Redis stream while nothing is reading it. 270 sent, and all 270 answered &lt;code&gt;202&lt;/code&gt;. Only 178 reached ClickHouse, so 92 were missing. Exit 1, with the missing paths listed.&lt;/p&gt;
&lt;p&gt;The second run is the reason the drill counts rows. Every request got a success response, and a third of the events still disappeared. A drill that only checked status codes would have passed it.&lt;/p&gt;
&lt;p&gt;:::note
Both broken runs are part of T15&apos;s acceptance criteria, so the verifier agent reran them before the task could be marked done.
:::&lt;/p&gt;
&lt;h2&gt;Then the server&lt;/h2&gt;
&lt;p&gt;The local runs proved the drill works. The criterion that mattered was a redeploy of production under 20 events a second, which I ran myself from the Mac.&lt;/p&gt;
&lt;p&gt;The first server run failed with exit 1, though the deploy itself lost nothing. 903 sent, 0 failed, and every one of the 798 accepted events was stored once. The other 105 got a &lt;code&gt;202&lt;/code&gt; with &lt;code&gt;X-Mieru-Dropped: unknown_site&lt;/code&gt;. The run had just created the drill site, and each ingest replica reloads its sites every 30 seconds on its own clock. The probe reached the replica that already knew the site, and round robin sent every other event to the one that didn&apos;t yet.&lt;/p&gt;
&lt;p&gt;So the preflight was wrong. The fix reads the site&apos;s age from Postgres and, while it&apos;s younger than 35 seconds, waits out the rest before sending anything. The second server run, after the fix:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;events sent      904, 745 of them during the deploy (42s)
answered 202     904
failed           0
dropped          0
stored           904 rows, 904 distinct paths
PASS: all 904 events were answered 202 and stored exactly once
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;What it doesn&apos;t prove&lt;/h2&gt;
&lt;p&gt;It&apos;s a correctness drill and makes no claim about load. One client sends at most 20 events a second, about 17 in practice, from one address. Load tests with k6 are planned after the MVP.&lt;/p&gt;
&lt;p&gt;One gap is still open. Caddy retries a POST only when the connection fails. A request sent on a keep-alive connection that a stopping replica has just closed can still fail, and one run at this rate may not hit that window. Fixing it means touching the Caddyfile or ingest, which was outside T15&apos;s allowed files.&lt;/p&gt;
&lt;p&gt;:::tip
The drill is meant to be rerun after any change to &lt;code&gt;deploy.sh&lt;/code&gt;, the Caddyfile, the app services in &lt;code&gt;compose.prod.yaml&lt;/code&gt;, or how ingest or the writer shut down. Each run adds about 900 rows to the drill&apos;s own site.
:::&lt;/p&gt;
&lt;p&gt;The script is &lt;a href=&quot;https://github.com/AntonBurduzha/mieru/blob/main/ops/drills/deploy-under-traffic.sh&quot;&gt;&lt;code&gt;ops/drills/deploy-under-traffic.sh&lt;/code&gt;&lt;/a&gt;, and the whole story, both server runs included, is in the T15 spec.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item><item><title>A GitHub Activity Calendar on a Static Site, Rebuilt Every Night</title><link>https://aburduzha.dev/posts/static-activity-calendar</link><guid isPermaLink="true">https://aburduzha.dev/posts/static-activity-calendar</guid><description>How the activity calendar on my home page went from a build-time fetch to a browser fetch and back, and why a nightly rebuild ended up the simplest way to keep it fresh.</description><pubDate>Tue, 01 Dec 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The home page of this site has a GitHub-style activity calendar: one square per day for the last 12 months, darker on busier days. The site itself is static. Astro builds it into HTML files, and Cloudflare Pages serves them. The calendar&apos;s data changes every day, and the HTML only changes when the site is rebuilt.&lt;/p&gt;
&lt;p&gt;It took me three versions to settle how those two fit together. The third one fetches the data at build time and rebuilds the site every night from a cron job. This post covers how it renders, how it updates, what it costs, and what I gave up for it.&lt;/p&gt;
&lt;h2&gt;Version 1: fetched at build, never refreshed&lt;/h2&gt;
&lt;p&gt;The theme I started from already had a calendar component. It fetched contributions from &lt;a href=&quot;https://github-contributions-api.jogruber.de&quot;&gt;github-contributions-api.jogruber.de&lt;/a&gt;, a free service that returns a year of GitHub contributions as JSON, right in the component&apos;s frontmatter. I added a JSON file of GitLab counts I had exported once and merged it into the GitHub numbers.&lt;/p&gt;
&lt;p&gt;The fetch ran during &lt;code&gt;npm run build&lt;/code&gt;, and Pages only builds when I push. If I didn&apos;t push for three weeks, the calendar stopped three weeks ago. The GitLab file never changed after I exported it. On a phone, the calendar showed its oldest months, and the newest ones, the interesting ones, were off-screen to the right.&lt;/p&gt;
&lt;h2&gt;Version 2: fetched in the browser&lt;/h2&gt;
&lt;p&gt;The API sends &lt;code&gt;access-control-allow-origin: *&lt;/code&gt;, so moving the fetch into a client script was easy. The data was fresh on every visit. The problems were on the page:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The block was empty until the response arrived, then popped in and pushed everything below it down. I hid it until the data came and added a reveal animation, which is extra code to fix a problem I had just created.&lt;/li&gt;
&lt;li&gt;Every visitor made a request to a third-party API, and the page shipped JavaScript to build the SVG.&lt;/li&gt;
&lt;li&gt;A search engine or link preview that doesn&apos;t run scripts saw no calendar.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Astro&apos;s built-in way to defer a component, &lt;code&gt;server:defer&lt;/code&gt;, needs a server adapter, and I wanted the site to stay plain static files.&lt;/p&gt;
&lt;h2&gt;Version 3: a content loader and a nightly rebuild&lt;/h2&gt;
&lt;p&gt;The calendar doesn&apos;t need to-the-minute data. Today&apos;s square can wait until tomorrow. So the fetch went back into the build, this time through Astro&apos;s Content Layer, and a cron job rebuilds the site every night.&lt;/p&gt;
&lt;h3&gt;The loader&lt;/h3&gt;
&lt;p&gt;A collection&apos;s loader runs at build time and writes entries into Astro&apos;s data store. Mine fetches the last 12 months and stores them as one entry:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Last 12 months of GitHub contributions, fetched at build time.
const activityCollection = defineCollection({
  loader: githubActivityLoader({ username: &apos;AntonBurduzha&apos; }),
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;load: async ({ store, logger, parseData }) =&amp;gt; {
  for (let attempt = 1; attempt &amp;lt;= ATTEMPTS; attempt++) {
    try {
      const response = await fetchLastYear(username);
      const data = await parseData({
        id: username,
        data: {
          total: response.total.lastYear ?? 0,
          contributions: response.contributions,
        },
      });
      store.clear();
      store.set({ id: username, data });
      return;
    } catch (error) {
      logger.warn(
        `Attempt ${attempt}/${ATTEMPTS} failed: ${(error as Error).message}`,
      );
      if (attempt &amp;lt; ATTEMPTS) {
        await new Promise((resolve) =&amp;gt; setTimeout(resolve, RETRY_DELAY_MS * attempt));
      }
    }
  }
  logger.warn(
    store.has(username)
      ? &apos;Keeping previously loaded activity.&apos;
      : &apos;No activity data: the calendar will be hidden.&apos;,
  );
},
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;parseData&lt;/code&gt; validates the data against a Zod schema, so a changed API format counts as a failed attempt instead of drawing a broken calendar. If all three attempts fail (2 and then 4 seconds apart), the store keeps the previous entry if it has one, and the build goes on either way. A broken third-party API never breaks a deploy.&lt;/p&gt;
&lt;h3&gt;Rendering&lt;/h3&gt;
&lt;p&gt;The component reads the collection and renders the SVG on the server:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;---
const [activity] = await getCollection(&apos;activity&apos;);
const calendar = activity ? renderCalendar(activity.data.contributions) : undefined;
---
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If there&apos;s no entry, nothing renders. There&apos;s no empty state or spinner, and the layout below doesn&apos;t move.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;renderCalendar&lt;/code&gt; in &lt;code&gt;src/activity.ts&lt;/code&gt; is a plain TypeScript function that returns an SVG string and a date range. It doesn&apos;t import anything from Astro, so it would work the same in a browser script. It does four things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Fills the gaps.&lt;/strong&gt; Every day between the first and last date gets an entry, with zero for the missing ones.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Groups days into weeks.&lt;/strong&gt; The list is left-padded so every column starts on a Sunday. The first column can have empty slots at the top, like on GitHub.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Computes the levels itself.&lt;/strong&gt; The API sends a level from 0 to 4 for each day, but the function recomputes them from the quartiles of my non-zero days. That was required in version 1, when GitLab counts were added and the API&apos;s levels no longer matched the totals. I kept it so the shade of a square always follows the count in its tooltip.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Takes its colors from the theme.&lt;/strong&gt; Level 0 is the theme&apos;s background, level 4 is its accent, and the steps between are &lt;code&gt;color-mix(in oklab, …)&lt;/code&gt; of the two CSS variables. The calendar follows the light and dark themes without a palette of its own, and it would follow any other theme too.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Month labels go over the first column of each month. A month at either edge with fewer than three columns loses its label, since the text wouldn&apos;t fit. Instead of a year on every label, the header shows the range, &lt;code&gt;Nov 2025 – Dec 2026&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The page has two small scripts. One scrolls the calendar to the right edge, so phones open on the newest weeks. The other is the tooltip: a single delegated &lt;code&gt;mouseover&lt;/code&gt; listener on the calendar instead of 367 listeners, one per square. It only starts on screens at least 1024 px wide, where there&apos;s a mouse to hover with.&lt;/p&gt;
&lt;h3&gt;The nightly rebuild&lt;/h3&gt;
&lt;p&gt;Cloudflare Pages has deploy hooks: a secret URL that starts a build of a branch when you POST to it. A Worker with a cron trigger calls it every night:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export default {
  async scheduled(_controller, env) {
    if (!env.DEPLOY_HOOK_URL) throw new Error(&apos;DEPLOY_HOOK_URL secret is not set&apos;);
    const response = await fetch(env.DEPLOY_HOOK_URL, { method: &apos;POST&apos; });
    if (!response.ok) {
      throw new Error(`Deploy hook failed: ${response.status} ${await response.text()}`);
    }
  },
};
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;aburduzha-daily-rebuild&quot;,
  &quot;main&quot;: &quot;src/index.js&quot;,
  &quot;triggers&quot;: { &quot;crons&quot;: [&quot;15 0 * * *&quot;] },
  &quot;observability&quot;: { &quot;enabled&quot;: true },
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The hook URL is a Worker secret, not something in the repo, because anyone with it can start builds. A failed call throws, so it shows up as a failed run in the Worker&apos;s logs.&lt;/p&gt;
&lt;p&gt;I also looked at GitHub Actions with a &lt;code&gt;schedule&lt;/code&gt; trigger. It needs no extra service, but scheduled runs can start late, and GitHub turns schedules off in a public repository with no activity for 60 days. A personal site can easily go two months without a commit.&lt;/p&gt;
&lt;h2&gt;What it costs&lt;/h2&gt;
&lt;p&gt;Nothing. The Pages free plan allows &lt;a href=&quot;https://developers.cloudflare.com/pages/platform/limits/&quot;&gt;500 builds a month&lt;/a&gt;, one at a time. The nightly rebuild uses about 31 of them, so there&apos;s plenty left for pushes. A Worker that runs once a day is well inside the Workers free plan, and a build takes a minute or two.&lt;/p&gt;
&lt;h2&gt;What I got&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;The calendar is in the HTML. No empty block, no layout shift, no animation to hide either of them.&lt;/li&gt;
&lt;li&gt;The only JavaScript for it is the tooltip and the scroll. No script fetches or draws anything.&lt;/li&gt;
&lt;li&gt;Visitors don&apos;t depend on a third-party API, and an API outage costs at most one night&apos;s update.&lt;/li&gt;
&lt;li&gt;Search engines and link previews see the same page people do.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;What I gave up&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Freshness.&lt;/strong&gt; The data is up to a day old. For a year of activity that doesn&apos;t matter. For a live status page it would.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;HTML size.&lt;/strong&gt; 367 &lt;code&gt;&amp;lt;rect&amp;gt;&lt;/code&gt;s with inline attributes come to about 77 KB of the home page&apos;s 103 KB of HTML. It compresses well, to about 4 KB gzipped, because the squares are nearly identical, but it&apos;s still the biggest thing on the page.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Builds that change nothing.&lt;/strong&gt; The site rebuilds every night even when the data is the same as yesterday. At this size it costs nothing, but a site with thousands of pages and a 15-minute build would feel it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A failed night can hide the calendar.&lt;/strong&gt; Astro keeps its data store in &lt;code&gt;node_modules/.astro&lt;/code&gt;. Locally that survives between builds, so a failed fetch keeps yesterday&apos;s data. On Pages I don&apos;t count on that cache being there, so if the API is down at 00:15 UTC, the calendar can be missing until the next night.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An unofficial data source.&lt;/strong&gt; The contributions API is a free service run by one person, not GitHub&apos;s own API. GitHub&apos;s GraphQL API has the same data, but it needs a token in the build environment, and I didn&apos;t want a secret in the Pages build for one widget.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One more thing to deploy.&lt;/strong&gt; The Worker lives in this repo but deploys separately with &lt;code&gt;wrangler&lt;/code&gt;, and the deploy hook is set up by hand in the dashboard. Both are written down in the deploy guide, because I won&apos;t remember them in a year.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When I&apos;d do it differently&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Approach&lt;/th&gt;
&lt;th&gt;When it fits&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Build time + scheduled rebuild&lt;/td&gt;
&lt;td&gt;Data that can be a day old, a static host, a fast build&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fetch in the browser&lt;/td&gt;
&lt;td&gt;Data that must be current to the minute, or different for each visitor&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Server rendering with a CDN cache (&lt;code&gt;s-maxage&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;Many pages use the data, or the build is too slow to run every day&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Rebuild on a webhook from the source&lt;/td&gt;
&lt;td&gt;The source can tell you when it changes, like a CMS&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;For a calendar of a year&apos;s activity, the first row fit. The whole setup is a loader, a render function and a dozen lines of Worker.&lt;/p&gt;
</content:encoded><author>Anton Burduzha</author></item></channel></rss>