<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aditya Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Aditya Kumar Singh on Medium]]></description>
        <link>https://medium.com/@adityakrsingh26?source=rss-5e24f1119e16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*80EQOiItD3iWvtjdF5wl-A.jpeg</url>
            <title>Stories by Aditya Kumar Singh on Medium</title>
            <link>https://medium.com/@adityakrsingh26?source=rss-5e24f1119e16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:27:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityakrsingh26/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Migrating Your Search API from POST to QUERY (Without Breaking Anything)]]></title>
            <link>https://adityakrsingh26.medium.com/migrating-your-search-api-from-post-to-query-without-breaking-anything-030637ef30a9?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/030637ef30a9</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 06:52:11 GMT</pubDate>
            <atom:updated>2026-07-25T06:52:11.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Rm-GbfCNMi60r26LbqfzQ.png" /></figure><p>Over the course of this series, we’ve explored what the HTTP QUERY method is, why it exists, how to implement it on both the server and client, and how it unlocks caching for complex search requests.</p><p>Now comes the question every engineering team eventually asks:</p><p><strong><em>“We already have a search API built with POST. How do we migrate without breaking existing clients?”</em></strong></p><p>Fortunately, migrating to QUERY is one of the lowest-risk API migrations you can make. You don&#39;t need a complete rewrite, you don&#39;t need to coordinate every client update, and you certainly don&#39;t need a &quot;big bang&quot; deployment.</p><p>Instead, you can introduce QUERY gradually, validate it in production, and roll it back at any time if necessary.</p><p>Let’s walk through the migration process.</p><h3>The Golden Rule: Add, Don’t Replace</h3><p>The biggest mistake teams make during API migrations is treating them as replacements.</p><p>Don’t.</p><p>A QUERY endpoint should initially <strong>coexist</strong> with your existing POST endpoint.</p><p>The reason this works so well is that both methods look almost identical:</p><ul><li>Same URL</li><li>Same request body</li><li>Same response format</li><li>Same search implementation</li></ul><p>The only thing that changes is the HTTP method and the additional semantics that come with it.</p><p>That means your endpoint can happily support both methods simultaneously:</p><ul><li>Existing clients continue sending POST.</li><li>New clients start sending QUERY.</li><li>Both execute the exact same search logic.</li></ul><p>No clients break, and no functionality changes.</p><p>This single design decision removes almost all migration risk.</p><h3>Step 1: Verify That Your Endpoint Is Truly Read-Only</h3><p>Before introducing QUERY, make sure your endpoint actually behaves like a search endpoint.</p><p>QUERY makes one important guarantee:</p><blockquote><strong><em>Executing the request must not change server state.</em></strong></blockquote><p>Audit your existing POST handler and ask:</p><ul><li>Does every search create an audit record?</li><li>Does it increment analytics counters that are part of your business logic?</li><li>Does it trigger notifications?</li><li>Does it update user data?</li></ul><p>If the answer is <strong>yes</strong>, your endpoint isn’t purely a search operation. In that case, either:</p><ul><li>Keep it on POST, or</li><li>Separate the read-only search logic from the state-changing behavior.</li></ul><p>Fortunately, most search APIs already satisfy this requirement. They simply used POST because the request body was too large or too complex for GET.</p><p>Those endpoints are excellent candidates for QUERY.</p><h3>Step 2: Share One Search Handler</h3><p>A clean migration doesn’t duplicate business logic. Instead, extract your search implementation into a shared function.</p><p>Both POST and QUERY should call that same function. Conceptually, the architecture becomes:</p><pre>POST  ─────┐<br>           │<br>           ▼<br>      Shared Search Logic<br>           ▲<br>           │<br>QUERY ─────┘</pre><p>Nothing inside your search engine changes. The only difference is the HTTP method that reaches it.</p><p>This approach provides two major benefits:</p><ul><li>Existing behavior remains untouched.</li><li>Bugs in the new QUERY path cannot affect current POST clients.</li></ul><p>You’re simply adding another doorway into the same room.</p><h3>Step 3: Enable QUERY-Specific Features</h3><p>Once both methods work, start enabling the capabilities that make QUERY valuable. Importantly, these enhancements should apply <strong>only</strong> to the QUERY path.</p><p>These include:</p><h4>Response Caching</h4><p>Generate an ETag and include appropriate cache-control headers. This allows intermediaries and clients to cache search responses and later revalidate them instead of recomputing the search.</p><p>For search-heavy systems, this is often the largest performance improvement you’ll see.</p><h4>Result Reuse</h4><p>Return a Location header that represents the search as its own resource.</p><p>Clients can later retrieve the same result using lightweight conditional GET requests. This is one of the most powerful optimizations introduced by QUERY.</p><h4>Strict Validation</h4><p>Validate:</p><ul><li>Content-Type</li><li>Request format</li><li>Unsupported media types</li><li>Malformed bodies</li></ul><p>Return proper HTTP status codes when validation fails.</p><p>Keeping this validation isolated to the QUERY implementation ensures existing POST clients continue behaving exactly as before.</p><h3>Step 4: Advertise QUERY Support</h3><p>Clients cannot use a feature they don’t know exists.</p><p>Your server should explicitly advertise support for QUERY.</p><p>The two standard mechanisms are:</p><ul><li>Include QUERY in the Allow header for OPTIONS requests.</li><li>Include the Accept-Query header describing the supported query formats.</li></ul><p>This enables clients to detect support instead of making assumptions.</p><p>Small change. Big usability improvement.</p><h3>Step 5: Update Clients Gradually</h3><p>On the client side, the migration should be just as conservative. The recommended strategy is:</p><ol><li>Attempt a QUERY request.</li><li>If the server or an intermediary rejects it, automatically retry using POST.</li></ol><p>The fallback is seamless because both methods send the exact same payload.</p><p>From the user’s perspective, nothing changes.</p><p>This approach also protects against infrastructure that hasn’t yet learned about the QUERY method, including:</p><ul><li>Older proxies</li><li>Corporate firewalls</li><li>API gateways</li><li>CDNs</li></ul><p>You can roll this change out client by client without coordinating a global release.</p><h3>Step 6: Measure Adoption</h3><p>Once both methods are available, simply observe usage. Track metrics such as:</p><ul><li>Percentage of traffic using QUERY</li><li>Percentage still using POST</li><li>Cache hit rates</li><li>Latency improvements</li><li>Error rates</li></ul><p>Over time, more clients will naturally migrate. Only then should you ask whether the POST endpoint is still necessary.</p><p>And honestly, it may never be worth removing.</p><p>Keeping POST as a permanent fallback is a perfectly reasonable long-term strategy.</p><p>The objective was never to eliminate POST. The objective was to make QUERY available to clients that can benefit from it.</p><h3>Real-World Considerations</h3><p>No migration is completely frictionless.</p><p>Here are a few practical issues worth checking before deployment.</p><h3>Older Infrastructure</h3><p>Some proxies, gateways, or firewalls may reject unfamiliar HTTP methods.</p><p>Test your own infrastructure early. If your CDN blocks QUERY, it&#39;s far better to discover that before your users do.</p><h3>Monitoring and Analytics</h3><p>Dashboards that filter requests by HTTP method may suddenly show a drop in search traffic.</p><p>Nothing disappeared. Your searches simply moved from POST to QUERY. Update dashboards and alerts accordingly.</p><h3>Caching Becomes Real</h3><p>With POST, caching was rarely a concern. With QUERY, it becomes a major feature. That also means cache configuration matters.</p><p>Ensure:</p><ul><li>User-specific responses are marked private.</li><li>Shared caches never expose personalized results.</li><li>Cache-control headers accurately describe response behavior.</li></ul><p>This is arguably the most important operational consideration during migration.</p><h3>Authentication and Rate Limiting</h3><p>Everything protecting your existing POST endpoint should also protect the new QUERY endpoint.</p><p>Verify that:</p><ul><li>Authentication</li><li>Authorization</li><li>Rate limiting</li><li>Quotas</li><li>Middleware</li></ul><p>apply consistently to both methods. A shared request pipeline usually makes this straightforward, but it’s still worth validating.</p><h3>Migration Checklist</h3><p>Before rolling out QUERY, confirm the following:</p><ul><li>✅ The endpoint is truly read-only.</li><li>✅ Search logic has been extracted into a shared handler.</li><li>✅ QUERY has been added alongside POST.</li><li>✅ ETag, caching, validation, and Location headers are enabled for QUERY.</li><li>✅ Allow and Accept-Query headers advertise support.</li><li>✅ Infrastructure correctly forwards QUERY.</li><li>✅ Monitoring includes the new HTTP method.</li><li>✅ Authentication and rate limiting apply equally.</li><li>✅ Clients prefer QUERY and gracefully fall back to POST.</li><li>✅ Adoption metrics are being tracked.</li></ul><h3>Rollback Is Trivial</h3><p>One of the strongest arguments for adopting QUERY is how easy it is to undo.</p><p>If any unexpected issue appears:</p><ul><li>Stop advertising QUERY.</li><li>Clients automatically return to POST.</li><li>Existing behavior remains exactly as before.</li></ul><p>Because you never replaced your original implementation, rollback requires almost no effort.</p><p>That’s the beauty of an additive migration.</p><p>The downside is tiny. The upside can be substantial.</p><h3>When You Shouldn’t Migrate</h3><p>Not every endpoint benefits from QUERY.</p><p>You probably don’t need it if:</p><ul><li>Your search parameters comfortably fit into a GET URL.</li><li>The endpoint performs state-changing operations.</li><li>The API is small, internal, and has little need for caching.</li></ul><p>QUERY delivers the most value for:</p><ul><li>Complex search requests</li><li>Large request bodies</li><li>Read-heavy APIs</li><li>Frequently repeated searches</li><li>Systems where caching significantly reduces computation</li></ul><p>Focus your migration efforts there first.</p><h3>Wrapping Up</h3><p>This series has explored the complete lifecycle of the HTTP QUERY method.</p><p>We covered:</p><ul><li>Why QUERY exists.</li><li>How to implement it correctly.</li><li>How clients should use it.</li><li>How it enables efficient caching.</li><li>How to migrate existing POST endpoints safely.</li></ul><p>With <strong>RFC 10008</strong> now published as a <strong>Proposed Standard</strong>, QUERY is no longer an experimental idea. Tooling is steadily improving, browser support is expanding, and server frameworks are beginning to adopt it.</p><p>For teams operating search-heavy APIs, this is one of those rare engineering upgrades that offers meaningful performance and architectural benefits while requiring only a small, reversible change.</p><p>If your search API still relies on POST solely because it needs a request body, now is a good time to start planning the transition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=030637ef30a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why HTTP QUERY Finally Makes Search Cacheable]]></title>
            <link>https://adityakrsingh26.medium.com/why-http-query-finally-makes-search-cacheable-a6addefbcdbd?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6addefbcdbd</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 19:45:22 GMT</pubDate>
            <atom:updated>2026-07-23T19:45:22.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZcxGZYAAZ1u6z250OZaQw.png" /></figure><p>So far in this series we’ve explored what HTTP QUERY is, how to implement it on the server, and how clients can use it. Now we get to the feature that makes QUERY genuinely valuable: <strong>caching</strong>.</p><p>This is also the easiest part of the series to understand. You don’t need to know much about HTTP internals to appreciate why it matters.</p><p>If you remember only one thing from this article, let it be this:</p><blockquote><strong><em>HTTP QUERY makes complex searches cacheable.</em></strong></blockquote><p>That means less work for your servers, fewer database queries, and applications that feel noticeably faster.</p><p>Let’s see why.</p><h3>A Quick Refresher: What Is a Cache?</h3><p>A cache is simply a temporary storage area for answers that have already been computed.</p><p>Instead of performing the same work every time someone asks the same question, the answer is stored somewhere nearby and reused.</p><p>Caches exist almost everywhere:</p><ul><li>Your browser</li><li>CDNs like Cloudflare</li><li>Reverse proxies</li><li>API gateways</li><li>Your own application</li></ul><p>If a cache already has the answer, the request never reaches your server. The response is returned almost instantly.</p><p>The challenge has always been trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3rqpwSj3Gme0xne4_0Z6g.png" /><figcaption>A cache serves previously computed responses whenever it can. Only cache misses reach the server.</figcaption></figure><p>A cache must know that reusing a previous response is safe. It needs confidence that the request won’t change anything and that sending the exact same request again would produce the same result.</p><p>HTTP QUERY provides exactly those guarantees.</p><h3>Why Search Was Traditionally Hard to Cache</h3><p>For years, APIs had two choices.</p><h4>Use GET</h4><p>GET works perfectly with caches because the entire request is represented by the URL.</p><pre>GET /products?category=books&amp;author=tolkien</pre><p>For simple searches, that’s ideal. The problem is that real-world searches rarely stay simple. Modern applications often need:</p><ul><li>dozens of filters</li><li>nested conditions</li><li>sorting options</li><li>pagination</li><li>complex search expressions</li></ul><p>Trying to fit all of that into a URL quickly becomes impractical.</p><h4>Use POST</h4><p>The natural alternative was POST.</p><pre>POST /products/search<br><br>{<br>  ...<br>}</pre><p>Now the search could be as large and structured as needed. Unfortunately, this solved one problem while creating another.</p><p>Caches generally assume a POST request might change server state.</p><p>Maybe it’s creating an order. Maybe it’s updating a user profile. Maybe it’s processing a payment.</p><p>Because caches can’t safely assume otherwise, they usually don’t reuse POST responses.</p><p>The result is that every search travels all the way to the server.</p><p>Even if ten thousand users perform exactly the same search, the application repeats the same work ten thousand times.</p><p>That’s a lot of unnecessary computation for requests that never modify any data.</p><h3>How HTTP QUERY Changes the Picture</h3><p>HTTP QUERY combines the advantages of both GET and POST.</p><p>Like POST, it supports a request body. Like GET, it is officially defined as <strong>safe</strong> and <strong>idempotent</strong>. Those two properties tell caches that the request is only reading data.</p><p>Once a response has been generated, it can safely be reused for identical requests.</p><p>The first request performs the work. Subsequent requests can often be answered directly from the cache.</p><p>For applications with many repeated searches, the performance improvement can be substantial.</p><p>Think about:</p><ul><li>dashboards</li><li>product catalogs</li><li>reporting systems</li><li>analytics tools</li><li>internal business applications</li></ul><p>These systems often receive the same queries repeatedly throughout the day.</p><h3>The One New Idea: The Request Body Is Part of the Cache Key</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUuUvdWXKvFmlDciwvyzdg.png" /><figcaption>With QUERY, the cache key is built from both the URL and the request body.</figcaption></figure><p>This is the biggest conceptual difference between QUERY and GET.</p><p>With GET, the URL uniquely identifies the request.</p><pre>GET /products?category=books</pre><p>The cache simply uses the URL as its lookup key.</p><p>QUERY is different.</p><pre>QUERY /products/search<br><br>{<br>    &quot;category&quot;: &quot;books&quot;<br>}</pre><p>Multiple requests can use the same URL while asking completely different questions. That means the cache has to identify requests using both the URL and the request body.</p><p>Think of it like filing documents.</p><p>With GET, the folder name alone tells you which document to retrieve.</p><p>With QUERY, several different documents can live in the same folder, so you also need to read the document title before finding the correct one.</p><p>The cache works the same way. Before it can decide whether it already has an answer, it must examine the request body.</p><p>That requires a little more work than GET caching, but it’s still far cheaper than executing the search again.</p><h3>Normalization: Improving Cache Hits</h3><p>Two clients can send logically identical searches that look slightly different.</p><p>For example, one client might list JSON properties in a different order. Another might include extra whitespace.</p><p>The searches mean exactly the same thing, but their request bodies are not identical.</p><p>A simple cache would treat them as completely different requests. To avoid this, some caches normalize request bodies before generating the cache key.</p><p>Normalization converts equivalent requests into a consistent representation, allowing more searches to reuse the same cached response.</p><p>However, normalization should be conservative. If two genuinely different searches are accidentally treated as identical, the cache will confidently return incorrect results.</p><p>A few extra cache misses are much better than returning the wrong data.</p><h3>A Better Optimisation: Give the Search Its Own URL</h3><p>Earlier in this series, we discussed an elegant optimisation. Instead of repeatedly sending the full QUERY request, the server can assign that search its own permanent URL.</p><p>The client performs the QUERY once. The server responds with a URL representing that specific search.</p><p>From then on, the client simply performs a normal GET request against that URL.</p><p>The expensive search description is transmitted only once. Every future request benefits from the mature caching behavior that already exists for GET.</p><p>It’s similar to bookmarking a frequently used search.</p><p>Describe it once. Reuse it forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XCeLcgkzWeOfaGA23Y89Q.png" /></figure><h3>Freshness: How Long Should Cached Results Live?</h3><p>Cached responses don’t last forever. Eventually the underlying data changes, so the server tells caches how long a response should be considered fresh.</p><p>You can think of this as a “best before” date.</p><p>For example:</p><ul><li>A product catalog that changes once a day can often be cached for an hour.</li><li>Inventory information might only stay accurate for a few seconds.</li><li>A live news feed may only be fresh for a minute or two.</li><li>Real-time sports scores may not be cacheable at all.</li></ul><p>There isn’t a single correct value. The right cache lifetime depends on two things:</p><ul><li>How frequently the data changes.</li><li>How much stale data your users can tolerate.</li></ul><p>Longer cache lifetimes reduce server load. Shorter lifetimes provide fresher data. Finding the right balance depends on your application.</p><h3>Public vs Private Caches</h3><p>Not every response should be shared. Some search results are identical for every user.</p><p>A public product search, for example, can safely be stored in a CDN. Other searches depend on the authenticated user.</p><p>Those responses belong only in that user’s browser cache.</p><p>Accidentally allowing personalized responses into a shared cache isn’t just a performance mistake.</p><p>It’s a privacy and security problem.</p><h3>Revalidation: Asking Before Downloading Again</h3><p>Even after a cached response expires, it may still be perfectly valid.</p><p>Instead of downloading everything again, the client can ask a much cheaper question:</p><blockquote><em>“Has anything changed since I last requested this?”</em></blockquote><p>If nothing has changed, the server responds with a lightweight <strong>304 Not Modified</strong> response.</p><p>The client continues using its existing copy.</p><p>Only when the data has actually changed does the server send the full response again.</p><p>For dashboards that refresh every few seconds, this dramatically reduces bandwidth and unnecessary work.</p><h3>Where Can QUERY Responses Be Cached?</h3><p>A QUERY response can be cached at multiple layers.</p><ul><li>The browser can cache responses for a single user.</li><li>A CDN can cache public responses for thousands of users.</li><li>A reverse proxy can protect your application from repeated requests.</li><li>Your application itself can cache expensive database queries.</li></ul><p>As long as responses are labeled correctly with freshness information and the appropriate public or private visibility, every layer can contribute to improving performance.</p><h3>A Practical Caching Strategy</h3><p>You don’t need an elaborate caching system to benefit from HTTP QUERY.</p><p>Start with a few simple guidelines.</p><ul><li>Cache popular searches that don’t change frequently.</li><li>Convert frequently repeated searches into permanent GET URLs whenever possible.</li><li>Keep user-specific responses private.</li><li>Use revalidation for pages that refresh often.</li><li>Normalize request bodies carefully, and only when it’s safe.</li></ul><p>These practices deliver most of the performance benefits without adding much complexity.</p><h3>Common Mistakes</h3><p>The most common mistake is allowing personalized search results into a shared cache. When in doubt, keep them private.</p><p>Another common problem is choosing cache lifetimes that don’t reflect how quickly the underlying data changes. Cache responses for too long and users see stale information. Cache them for too short a time and you lose much of the benefit.</p><p>Normalization can also cause trouble if it’s too aggressive. Treating different searches as identical leads to incorrect results.</p><p>Finally, remember that the request body is part of the cache key. If a cache starts returning results for the wrong search, an incomplete cache key is often the first thing to investigate.</p><h3>What’s Next?</h3><p>In <strong>Part 5</strong>, we’ll look at how to migrate existing POST-based search endpoints to HTTP QUERY without breaking existing clients.</p><p>You’ll see a practical migration strategy that lets older clients continue using POST while newer clients take advantage of QUERY’s safety, idempotency, and caching benefits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6addefbcdbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling HTTP QUERY from the Client: fetch, CORS, and Graceful Fallback]]></title>
            <link>https://adityakrsingh26.medium.com/calling-http-query-from-the-client-fetch-cors-and-graceful-fallback-877fa1d84d51?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/877fa1d84d51</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 18:44:10 GMT</pubDate>
            <atom:updated>2026-07-23T18:44:10.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9527X_8fx1H7xlQnDFNmQ.png" /></figure><p><a href="https://adityakrsingh26.medium.com/what-is-the-http-query-method-the-complete-guide-to-the-webs-newest-verb-82662f937205?sharedUserId=adityakrsingh26">Part 1</a> explained what the HTTP QUERY method is, and <a href="https://medium.com/@adityakrsingh26/implementing-http-query-on-the-server-a-practical-guide-16ebaccf2b95?sharedUserId=adityakrsingh26">Part 2</a> built a correct server endpoint for it. <br>Now we cross to the other side of the wire: making QUERY requests from a browser (and other clients), handling the responses properly, and doing it all without breaking when a server or an intermediary doesn’t yet understand the method.</p><p>QUERY is new enough (RFC 10008 landed in June 2026) that “will this actually reach the server?” is a real question. So this part is as much about <em>resilience</em> feature detection and fallback as it is about the happy path.</p><h3>The happy path: a QUERY with fetch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Aqjqg2okczEyuI656Le0w.png" /><figcaption>QUERY Request Lifecycle</figcaption></figure><p>The fetch API accepts an arbitrary method string, and QUERY is not on the list of methods browsers forbid, so the basic call is refreshingly ordinary:</p><pre>const res = await fetch(&#39;/contacts&#39;, {<br>  method: &#39;QUERY&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>    &#39;Accept&#39;: &#39;application/json&#39;,<br>  },<br>  body: new URLSearchParams({ select: &#39;surname,email&#39;, limit: &#39;10&#39; }),<br>});<br><br>if (res.ok) {<br>  const contacts = await res.json();<br>}</pre><p>Two things to get right from the start:</p><ul><li><strong>Use uppercase </strong><strong>QUERY.</strong> Fetch normalizes a handful of well-known methods to uppercase, but custom methods are sent verbatim. Lowercase query may not be recognized by a strict server.</li><li><strong>The </strong><strong>Content-Type must match the body.</strong> As we saw in Part 2, the server won&#39;t sniff if you send form data, say so; if you send SQL, use application/sql. A mismatch earns a 400.</li></ul><p>That’s the whole happy path. Everything below is about making it robust in the real world.</p><h3>The CORS preflight you can’t avoid</h3><p>If your request is cross-origin the page is on app.example.com and the API is on api.example.com the browser will send a <strong>preflight </strong><strong>OPTIONS</strong> before your QUERY.</p><p>This is not optional and not something the client can turn off: QUERY is not one of the three CORS - &quot;safelisted&quot; methods (GET, HEAD, POST), so any QUERY across origins is a &quot;non-simple&quot; request by definition.</p><p>The preflight looks like this, sent automatically by the browser:</p><pre>OPTIONS /contacts HTTP/1.1<br>Origin: https://app.example.com<br>Access-Control-Request-Method: QUERY<br>Access-Control-Request-Headers: content-type</pre><p>For your QUERY to proceed, the server’s preflight response must approve it (this is server config from <a href="https://medium.com/@adityakrsingh26/implementing-http-query-on-the-server-a-practical-guide-16ebaccf2b95?sharedUserId=adityakrsingh26">Part 2</a>, but you need to recognize the failure mode):</p><pre>Access-Control-Allow-Origin: https://app.example.com<br>Access-Control-Allow-Methods: GET, QUERY, OPTIONS<br>Access-Control-Allow-Headers: Content-Type, Accept</pre><p>What you <em>can</em> control on the client:</p><ul><li><strong>Keep request headers minimal.</strong> Every non-safelisted header you add widens what the preflight must approve.</li><li><strong>Expect the latency.</strong> The preflight is a full extra round trip on the first request. Browsers cache the preflight result per Access-Control-Max-Age, so subsequent QUERYs skip it but design for that first hit.</li><li><strong>Recognise the symptom.</strong> If your QUERY “fails” with a CORS error in the console but you never see it hit the server logs, the preflight was rejected. That’s a server-config problem, not a client bug.</li></ul><h3>Don’t assume support, feature-detect it</h3><p>Because QUERY is still rolling out, a robust client checks whether a resource supports it before committing. There are two signals, both introduced across Parts 1 and 2:</p><ul><li>The <strong>Accept-Query</strong> response header on a GET/HEAD its presence means the resource speaks QUERY, and its value lists the accepted query formats.</li><li>The <strong>Allow</strong> header on an OPTIONS response if it lists QUERY, you&#39;re good.</li></ul><p>A lightweight probe using HEAD (which is CORS-safelisted, so no preflight of its own):</p><pre>async function detectQuerySupport(url) {<br>  try {<br>    const res = await fetch(url, { method: &#39;HEAD&#39; });<br>    const acceptQuery = res.headers.get(&#39;Accept-Query&#39;);<br>    if (acceptQuery) <br>        return { supported: true, formats: acceptQuery };<br><br>    const allow = res.headers.get(&#39;Allow&#39;) || &#39;&#39;;<br>    const methods = allow.split(&#39;,&#39;).map((m) =&gt; m.trim().toUpperCase());<br>    return { supported: methods.includes(&#39;QUERY&#39;), formats: null };<br>  <br>  } catch {<br>    return { supported: false, formats: null };<br>  }<br>}</pre><p>One cross-origin caveat: to read Accept-Query (or Allow, Location, ETag) from JavaScript on a cross-origin response, the server must expose them with Access-Control-Expose-Headers. If your probe sees an empty header that you <em>know</em> the server sends, that missing exposure is why.</p><p>Cache the detection result per origin so you’re not probing before every call.</p><h3>Graceful degradation: fall back to POST</h3><p>Feature detection tells you what a <em>cooperating</em> server supports. But QUERY can also be blocked by something in the middle an old proxy, a CDN, or a WAF that drops unfamiliar methods, often returning 405 Method Not Allowed or 501 Not Implemented.</p><p>A resilient client handles both cases by falling back to a plain POST with the identical body:</p><pre>async function queryWithFallback(url, { contentType, body, accept = &#39;application/json&#39; }) {<br>  <br>  const send = (method) =&gt;<br>    fetch(url, {<br>      method,<br>      headers: { &#39;Content-Type&#39;: contentType, Accept: accept },<br>      body,<br>    });<br><br>  let res;<br>  <br>  try {<br>    res = await send(&#39;QUERY&#39;);<br>  } catch (networkErr) {<br>    // Network layer refused the method outright<br>    return send(&#39;POST&#39;);<br>  }<br><br>  // Intermediary or server rejected the method itself<br>  if (res.status === 405 || res.status === 501) {<br>    return send(&#39;POST&#39;);<br>  }<br>  return res;<br>}</pre><p>The body doesn’t change between the two only the method doesso the fallback is a genuine drop-in.</p><p>You lose QUERY’s caching and idempotency guarantees on the fallback path, but you keep the feature working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*J7HDuz-fEo-2VvfD6dD88w.png" /></figure><h3>Retries are safe now use them</h3><p>Here’s a client-side payoff that’s easy to miss. Because QUERY is <strong>idempotent</strong>, you can safely retry it after a timeout or a 5xx something you should never do blindly with POST, where a retry risks double-submitting.</p><p>This makes QUERY genuinely better for flaky-network search:</p><pre>async function queryWithRetry(url, opts, { retries = 2, backoffMs = 300 } = {}) {<br>  for (let attempt = 0; ; attempt++) {<br>    try {<br>      const res = await fetch(url, { method: &#39;QUERY&#39;, ...opts });<br>      if (res.status &gt;= 500 &amp;&amp; attempt &lt; retries) {<br>        await new Promise((r) =&gt; setTimeout(r, backoffMs * 2 ** attempt));<br>        continue;<br>      }<br>      return res;<br>    } catch (err) {<br>      if (attempt &gt;= retries) throw err;<br>      await new Promise((r) =&gt; setTimeout(r, backoffMs * 2 ** attempt));<br>    }<br>  }<br>}</pre><p>Pair this with an AbortController so a hung request doesn&#39;t block a retry:</p><pre>function withTimeout(ms) {<br>  const ctrl = new AbortController();<br>  const id = setTimeout(() =&gt; ctrl.abort(), ms);<br>  return { signal: ctrl.signal, done: () =&gt; clearTimeout(id) };<br>}<br><br>const t = withTimeout(5000);<br>try {<br>  const res = await fetch(&#39;/contacts&#39;, { method: &#39;QUERY&#39;, signal: t.signal, /* ... */ });<br>} finally {<br>  t.done();<br>}</pre><h3>Reading the response like a QUERY client should</h3><p>The status codes from <a href="https://medium.com/@adityakrsingh26/implementing-http-query-on-the-server-a-practical-guide-16ebaccf2b95?sharedUserId=adityakrsingh26">Part 2</a> each map to a client action. Handle them deliberately rather than treating everything non-200 as a generic failure:</p><ul><li><strong>200 OK</strong> : parse the body in the type you asked for.</li><li><strong>400 Bad Request</strong> : your Content-Type was missing or didn&#39;t match the body. Fix the request; don&#39;t retry as-is.</li><li><strong>415 Unsupported Media Type</strong> : the server doesn&#39;t accept that query language.</li><li><strong>406 Not Acceptable</strong> : the server can&#39;t produce your requested response type. Relax your Accept.</li><li><strong>422 Unprocessable Content</strong> : the query was valid but unfulfillable. Surface this to the user; retrying won&#39;t help.</li><li><strong>304 Not Modified</strong> : only on a conditional request; your cached results are still current.</li></ul><p>Renegotiating after a 415 is a nice touch:</p><pre>async function queryNegotiating(url, formats, accept = &#39;application/json&#39;) {<br>  for (const { contentType, body } of formats) {<br>    const res = await fetch(url, {<br>      method: &#39;QUERY&#39;,<br>      headers: { &#39;Content-Type&#39;: contentType, Accept: accept },<br>      body,<br>    });<br>    if (res.status !== 415) <br>        return res; // success or a different error<br>    // else: server told us via Accept-Query it wants another format — try next<br>  }<br>  throw new Error(&#39;No mutually supported query format&#39;);<br>}</pre><h3>Consuming the result-reuse pattern</h3><p>Part 2’s server hands back a Location (the query as an addressable resource) and an ETag. The client&#39;s job is to <em>use</em> them: run the expensive QUERY once, then poll cheaply with conditional GET.</p><pre>// 1) Run the query once<br>const res = await fetch(&#39;/contacts&#39;, {<br>  method: &#39;QUERY&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;, Accept: &#39;application/json&#39; },<br>  body: new URLSearchParams({ match: &#39;active=true&#39; }),<br>});<br><br>let results = await res.json();<br>const queryUrl = res.headers.get(&#39;Location&#39;); // e.g. /contacts/queries/42<br>let etag = res.headers.get(&#39;ETag&#39;);<br><br>// 2) Later, refresh without resending the body<br>async function refresh() {<br>  if (!queryUrl) return results; // server didn&#39;t offer an equivalent resource<br>  const r = await fetch(queryUrl, {<br>    headers: etag ? { &#39;If-None-Match&#39;: etag } : {},<br>  });<br>  if (r.status === 304) return results; // unchanged — nothing to do<br>  etag = r.headers.get(&#39;ETag&#39;);<br>  results = await r.json();<br>  return results;<br>}</pre><p>This is the shape you want for dashboards and live filters: one QUERY to establish the search, then a stream of near-free GETs that mostly return 304.</p><p>Remember the cross-origin caveat Location and ETag must be listed in Access-Control-Expose-Headers for the client to read them.</p><h3>Sending richer query languages</h3><p>The form-encoded example is the simplest, but the client side is identical for any format set the matching Content-Type and put the query in the body.</p><p>A JSONPath search:</p><pre>const res = await fetch(&#39;/errata.json&#39;, {<br>  method: &#39;QUERY&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/jsonpath&#39;, Accept: &#39;application/json&#39; },<br>  body: &#39;$..[?@.status==&quot;Rejected&quot; &amp;&amp; @.date&gt;&quot;2024&quot;][&quot;doc-id&quot;]&#39;,<br>});</pre><p>The rule never changes: the body defines the query, and the Content-Type names its language. Let Accept-Query (from detection) tell you which languages a given endpoint will take.</p><h3>Non-browser clients</h3><p>Outside the browser, life is easier there’s no CORS and usually no method restrictions:</p><ul><li><strong>Node (built-in </strong><strong>fetch/undici)</strong> accepts method: &#39;QUERY&#39; directly, same as the browser examples, minus the preflight.</li><li><strong>curl</strong> uses -X QUERY (shown in Part 2&#39;s testing section).</li><li><strong>HTTP libraries</strong> in most languages accept a custom method string; check that your library and any proxy in front of it forward unknown methods rather than rejecting them.</li></ul><p>The main portability risk in every environment is the same: an intermediary that doesn’t pass the method through. The 405/501 fallback covers it.</p><h3>A reusable client, all together</h3><p>Combining detection, fallback, retries, and result reuse into one helper:</p><pre>const supportCache = new Map();<br><br>async function smartQuery(url, { contentType, body, accept = &#39;application/json&#39; }) {<br>  // 1) Detect once per origin<br>  const origin = new URL(url, location.href).origin;<br>  if (!supportCache.has(origin)) {<br>    supportCache.set(origin, await detectQuerySupport(url));<br>  }<br>  const { supported } = supportCache.get(origin);<br><br>  const headers = { &#39;Content-Type&#39;: contentType, Accept: accept };<br><br>  // 2) Use POST directly if we know QUERY isn&#39;t supported<br>  if (!supported) {<br>    return fetch(url, { method: &#39;POST&#39;, headers, body });<br>  }<br><br>  // 3) QUERY with retry, and a status-code fallback for middleboxes<br>  const res = await queryWithRetry(url, { headers, body });<br>  if (res.status === 405 || res.status === 501) {<br>    return fetch(url, { method: &#39;POST&#39;, headers, body });<br>  }<br>  return res;<br>}</pre><p>That’s a production-shaped entry point: it prefers QUERY, exploits its idempotency with retries, and never leaves a user stranded when the method can’t get through.</p><h3>What’s next</h3><ul><li><strong>Part 4 — Caching strategies in depth.</strong> How body-based cache keys work, safe normalization, Vary, and squeezing the most out of the Location/Content-Location pattern across browsers, CDNs, and shared caches.</li><li><strong>Part 5 — Migrating POST-based search endpoints to QUERY</strong> without breaking existing clients — combining everything from the server and client sides of this series.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=877fa1d84d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing HTTP QUERY on the Server: A Practical Guide]]></title>
            <link>https://adityakrsingh26.medium.com/implementing-http-query-on-the-server-a-practical-guide-16ebaccf2b95?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ebaccf2b95</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 08:31:01 GMT</pubDate>
            <atom:updated>2026-07-06T08:31:01.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68PqhdywfyDWgX9luA1Q4Q.png" /></figure><p>In <a href="https://medium.com/@adityakrsingh26/what-is-the-http-query-method-the-complete-guide-to-the-webs-newest-verb-82662f937205?sharedUserId=adityakrsingh26">Part 1</a> we covered <em>what</em> the HTTP QUERY method is and <em>why</em> it exists: a request method that carries a body like POST but stays safe and idempotent like GET, standardised in <strong>RFC 10008</strong> in June 2026.</p><p>This part is hands-on. We&#39;re going to build a QUERY endpoint the right way one that validates strictly, returns the correct status codes, advertises itself, and plays nicely with caches.</p><p>The examples use Javascript, Python and Go, but the principles are framework-agnostic. If you can read one, you can translate to your stack.</p><h3>The one rule you must not break</h3><p>Before any code: QUERY is <strong>safe</strong> and <strong>idempotent</strong>.</p><p>That’s not a suggestion it’s the contract the entire ecosystem relies on. Caches, proxies, and client retry logic will treat your endpoint as side-effect-free and freely repeatable.</p><p>So the single hard rule of implementing QUERY is: <strong>your handler must not change server state.</strong> No writes, no counters that matter, no “creating a record as a side effect of searching.”</p><p>If your operation needs to mutate something, it isn’t a QUERY it’s a POST. Everything else in this guide assumes you&#39;ve honored this.</p><p>A subtle exception the spec explicitly allows: a QUERY handler <em>may</em> create a helper resource to hold or represent the results (so clients can fetch them later with GET). That&#39;s fine, because the <em>queried</em> resource is unchanged and re-running the query yields the same effect. We&#39;ll implement that pattern near the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSBSQmxT0xPNkDESz_P5CQ.png" /></figure><h3>Step 1 : Routing a brand-new method</h3><p>Most web frameworks were designed around the classic verb set, so their routing sugar (app.get, app.post) often doesn&#39;t know about QUERY yet. The reliable approach is to inspect the request method yourself.</p><p>The good news: the underlying HTTP servers in Node, Python, and Go all accept arbitrary method tokens on the wire it&#39;s only the high-level routers that need coaxing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jS7k3jOFiNlAv4zWiLhOpw.png" /></figure><ul><li><strong>Node / Express</strong> : check the method in middleware, and capture the raw body yourself (don’t let a body parser make assumptions about a method it’s never heard of):</li></ul><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>// Buffer the raw body for QUERY requests<br>app.use((req, res, next) =&gt; {<br>  if (req.method !== &#39;QUERY&#39;) return next();<br>  const chunks = [];<br>  req.on(&#39;data&#39;, (c) =&gt; chunks.push(c));<br>  req.on(&#39;end&#39;, () =&gt; {<br>    req.rawBody = Buffer.concat(chunks);<br>    next();<br>  });<br>});<br><br>// Route QUERY /contacts to our handler<br>app.use(&#39;/contacts&#39;, (req, res, next) =&gt; {<br>  if (req.method === &#39;QUERY&#39;) return handleContactsQuery(req, res);<br>  next();<br>});</pre><ul><li><strong>Python / Starlette (or FastAPI)</strong> : Starlette’s Route accepts arbitrary method strings:</li></ul><pre>from starlette.applications import Starlette<br>from starlette.routing import Route<br>from starlette.responses import JSONResponse<br><br>async def contacts_query(request):<br>    body = await request.body()<br>    ...  # handled below<br><br>routes = [Route(&quot;/contacts&quot;, contacts_query, methods=[&quot;QUERY&quot;])]<br>app = Starlette(routes=routes)</pre><ul><li><strong>Go: </strong>the standard library dispatches on r.Method, which is just a string:</li></ul><pre>func contactsHandler(w http.ResponseWriter, r *http.Request) {<br>    switch r.Method {<br>    case &quot;QUERY&quot;:<br>        handleContactsQuery(w, r)<br>    case http.MethodGet:<br>        handleContactsGet(w, r)<br>    case http.MethodOptions:<br>        writeAllow(w)<br>    default:<br>        w.Header().Set(&quot;Allow&quot;, &quot;GET, QUERY, OPTIONS, HEAD&quot;)<br>        http.Error(w, &quot;method not allowed&quot;, http.StatusMethodNotAllowed)<br>    }<br>}</pre><p>Note the default branch already handles one of our status codes: <strong>405 Method Not Allowed</strong>, with an Allow header. Always send Allow on a 405 so clients learn what the resource <em>does</em> support.</p><h3>Step 2 : Validate Content-Type strictly (no sniffing)</h3><p>This is where a lot of naive implementations go wrong. RFC 10008 is emphatic: the request body’s meaning comes from its Content-Type, and the server <strong>must not</strong> guess.</p><p>If the media type is missing, or is present but doesn&#39;t match the actual body, that&#39;s a client error return <strong>400 Bad Request</strong>. If the media type is well-formed but your endpoint doesn&#39;t support that query language, return <strong>415 Unsupported Media Type</strong>.</p><p>Two different errors for two different problems. Don’t collapse them.</p><p><strong>Javascript:</strong></p><pre>const SUPPORTED_QUERY_TYPES = new Set([<br>  &#39;application/x-www-form-urlencoded&#39;,<br>  &#39;application/sql&#39;,<br>]);<br><br>function handleContactsQuery(req, res) {<br>  const contentType = (req.headers[&#39;content-type&#39;] || &#39;&#39;).split(&#39;;&#39;)[0]<br>                                                         .trim()<br>                                                         .toLowerCase();<br><br>  // No media type at all → malformed QUERY<br>  if (!contentType) {<br>    return res.status(400)<br>              .json({ error: &#39;QUERY requires a Content-Type header&#39; });<br>  }<br><br>  // Media type we don&#39;t handle here → 415, and advertise what we do handle<br>  if (!SUPPORTED_QUERY_TYPES.has(contentType)) {<br>    res.set(<br>        &#39;Accept-Query&#39;, <br>        &#39;&quot;application/x-www-form-urlencoded&quot;, &quot;application/sql&quot;&#39;<br>    );<br>    return res.status(415)<br>              .json({ error: `Unsupported query format: ${contentType}` });<br>  }<br><br>  // ...parse and process (Step 3)<br>}</pre><p>The 415 response does double duty: it rejects the request <em>and</em> teaches the client what to send next via Accept-Query. That&#39;s the polite, discoverable behavior we&#39;ll formalize in Step 6.</p><h3>Step 3 : Parse the body by its media type</h3><p>Because the media type selects the query language, your handler becomes a small dispatcher. Keep each parser isolated so adding a new supported format later is a one-line change.</p><p><strong>Javascript:</strong></p><pre>function parseQuery(contentType, rawBody) {<br><br>  const text = rawBody.toString(&#39;utf8&#39;);<br><br>  switch (contentType) {<br>    case &#39;application/x-www-form-urlencoded&#39;:<br>      return { kind: &#39;form&#39;, params: new URLSearchParams(text) };<br>    case &#39;application/sql&#39;:<br>      return { kind: &#39;sql&#39;, sql: text };<br>    default:<br>      // Should never reach here — Step 2 already filtered<br>      throw new Error(&#39;unreachable&#39;);<br>  }<br><br>}</pre><p>If you accept SQL as a query language, do <strong>not</strong> pass it through to your database verbatim treat it as untrusted input, parse it, and map it onto a constrained, parameterised query surface you control.</p><h3>Step 4 : Produce the response and negotiate the type</h3><p>The client tells you what response format it wants via the ordinary Accept header. If you can&#39;t produce any of the types it will accept, return <strong>406 Not Acceptable</strong>. Otherwise, run the query (remember: read-only), serialize the results, and return <strong>200 OK</strong> with the results in the body.</p><p><strong>Javascript:</strong></p><pre>function respondWithResults(req, res, results) {<br>  const accept = req.headers[&#39;accept&#39;] || &#39;application/json&#39;;<br><br>  if (accept.includes(&#39;application/json&#39;) || accept.includes(&#39;*/*&#39;)) {<br>    const body = JSON.stringify(results);<br>    res.set(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>    res.set(&#39;Vary&#39;, &#39;Accept&#39;);        // response depends on Accept<br>    return res.status(200).send(body);<br>  }<br><br>  if (accept.includes(&#39;text/csv&#39;)) {<br>    res.set(&#39;Content-Type&#39;, &#39;text/csv&#39;);<br>    res.set(&#39;Vary&#39;, &#39;Accept&#39;);<br>    return res.status(200).send(toCsv(results));<br>  }<br><br>  return res.status(406).json({ error: &#39;No acceptable response format&#39; });<br>}</pre><p>Setting Vary: Accept tells caches that responses differ by requested type important once you start negotiating multiple output formats.</p><h3>Step 5 : The full status-code map</h3><p>Putting the pieces together, here’s the decision flow your handler should implement, in order:</p><ul><li><strong>No </strong><strong>Content-Type, or it doesn&#39;t match the body</strong> — 400 Bad Request.</li><li><strong>Content-Type is a query format you don&#39;t support</strong> — 415 Unsupported Media Type (include Accept-Query).</li><li><strong>You can’t produce any response type the client will </strong><strong>Accept</strong> — 406 Not Acceptable.</li><li><strong>The query is well-formed and supported, but can’t be fulfilled</strong> (e.g. valid SQL referencing a table that doesn’t exist) — 422 Unprocessable Content.</li><li><strong>The method isn’t allowed on this resource at all</strong> — 405 Method Not Allowed (include Allow).</li><li><strong>Everything worked</strong> — 200 OK, results in the body.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuVHv-1dlxr9Xq0Ms9-3Bw.png" /></figure><p>That 422 is the one people forget. It&#39;s the &quot;your request was perfectly valid, I just can&#39;t answer it&quot; case, and it&#39;s distinct from a 400 (malformed) or a 415 (wrong format).</p><h3>Step 6 : Advertise that you support QUERY</h3><p>Clients shouldn’t have to guess. There are two complementary ways to make your support discoverable, and you should do both.</p><p><strong>Respond to </strong><strong>OPTIONS with an </strong><strong>Allow header</strong> listing every method the resource supports:</p><p><strong>go:</strong></p><pre>func writeAllow(w http.ResponseWriter) {<br>    w.Header().Set(&quot;Allow&quot;, &quot;GET, QUERY, OPTIONS, HEAD&quot;)<br>    w.WriteHeader(http.StatusNoContent)<br>}</pre><p><strong>Emit the </strong><strong>Accept-Query header</strong> on responses to GET/HEAD (and, as we saw, on 415s). It announces that the resource accepts QUERY <em>and</em> which query-format media types it understands:</p><pre>Accept-Query: &quot;application/x-www-form-urlencoded&quot;, &quot;application/sql&quot;</pre><p>One important detail: Accept-Query is a <strong>structured field</strong>, not a loose comma list like the classic Accept header. Format it accordingly quote the media-type members, and don&#39;t rely on ordering to convey preference (order isn&#39;t significant).</p><h3>Step 7 : Make results reusable with Location and Content-Location</h3><p>This is the pattern that turns a good QUERY endpoint into a great one. On a successful response you can hand the client one or both of:</p><ul><li><strong>Content-Location</strong> : a URL for <em>this exact result set</em> (a snapshot the client can GET again).</li><li><strong>Location</strong>: a URL for <em>the query itself</em>, such that a plain GET to it re-runs the same query and returns fresh results, with no body required.</li></ul><p><strong>Javascript</strong></p><pre>function respondWithReusableResults(req, res, results, queryId, resultId) {<br>  const etag = computeEtag(results);<br>  res.set(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>  res.set(&#39;ETag&#39;, etag);<br>  res.set(&#39;Content-Location&#39;, `/contacts/results/${resultId}`);<br>  res.set(&#39;Location&#39;, `/contacts/queries/${queryId}`);<br>  res.set(&#39;Cache-Control&#39;, &#39;private, max-age=60&#39;);<br>  return res.status(200).send(JSON.stringify(results));<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmqmFxumGcA22jApSO24eA.png" /></figure><p>Now the client can stop resending the body: after the first QUERY, it switches to conditional GETs against the LocationURL. This is the efficient long-term shape pay for the full query once, then poll cheaply.</p><h3>Step 8 : Caching and conditional requests</h3><p>Responses to QUERY are cacheable, which is the whole payoff over the old POST hack. Two things make caching work correctly:</p><p><strong>Emit validators.</strong> Return an ETag (or Last-Modified) on results so clients and caches can revalidate. When a client sends If-None-Match with your ETag and nothing has changed, reply 304 Not Modified with an empty body:</p><p><strong>Javascript:</strong></p><pre>function maybeNotModified(req, res, etag) {<br>  if (req.headers[&#39;if-none-match&#39;] === etag) {<br>    res.status(304).end();<br>    return true;<br>  }<br>  return false;<br>}</pre><p><strong>Understand the cache key.</strong> For QUERY, a compliant cache keys on the request URL <strong>plus the request body and its metadata</strong> because the body is what distinguishes one query from another. You don’t implement that in your handler, but you should design with it in mind: keep query bodies canonical where you can, and prefer the Location-to-GETpattern for anything hot, so ordinary URL-based caching takes over.</p><p>If a query is expensive and its results are shareable, use Cache-Control: public; if results are user-specific, use private. Never mark user-scoped results public.</p><h3>A note on CORS</h3><p>If browsers will call your endpoint cross-origin, QUERY is <strong>not</strong> on the CORS safelist, so the browser sends a preflight OPTIONS. Your preflight response must include QUERY in the allowed methods:</p><pre>Access-Control-Allow-Origin: https://app.example.com<br>Access-Control-Allow-Methods: GET, QUERY, OPTIONS<br>Access-Control-Allow-Headers: Content-Type, Accept</pre><p>Miss this and your front end will fail before the QUERY ever reaches your handler. We’ll cover the client side in detail in Part 3.</p><h3>Security checklist for implementers</h3><ul><li><strong>Treat the query body as untrusted input.</strong> If you accept a query language like SQL or JSONPath, parse and validate it against a constrained surface — never forward raw client SQL to your database.</li><li><strong>Enforce limits.</strong> Cap body size, execution time, and result size. A safe method is still a resource-consumption vector; a maliciously expensive query is a denial-of-service risk.</li><li><strong>Don’t leak sensitive input into generated URLs.</strong> If a query contained sensitive terms, the Location/Content-Location URLs you mint must not embed those terms.</li><li><strong>Scope caching correctly.</strong> Anything user-specific is private. Double-check you&#39;re not caching authorized results where another user could receive them.</li><li><strong>Keep it genuinely read-only.</strong> Audit your handler for accidental writes (lazy-created records, analytics side effects that matter, cache-population that changes behavior).</li></ul><h3>Putting it together</h3><p>A minimal but correct handler, end to end:</p><pre>function handleContactsQuery(req, res) {<br>  const contentType = (req.headers[&#39;content-type&#39;] || &#39;&#39;)<br>    .split(&#39;;&#39;)[0].trim().toLowerCase();<br><br>  if (!contentType)<br>    return res.status(400).json({ error: &#39;Content-Type required&#39; });<br><br>  if (!SUPPORTED_QUERY_TYPES.has(contentType)) {<br>    res.set(&#39;Accept-Query&#39;, &#39;&quot;application/x-www-form-urlencoded&quot;, &quot;application/sql&quot;&#39;);<br>    return res.status(415).json({ error: &#39;Unsupported query format&#39; });<br>  }<br><br>  let parsed;<br>  try {<br>    parsed = parseQuery(contentType, req.rawBody);<br>  } catch {<br>    return res.status(400).json({ error: &#39;Malformed query body&#39; });<br>  }<br><br>  let results;<br>  try {<br>    results = runReadOnlyQuery(parsed);      // must not mutate state<br>  } catch (e) {<br>    if (e.code === &#39;UNFULFILLABLE&#39;)<br>      return res.status(422).json({ error: &#39;Query cannot be processed&#39; });<br>    throw e;<br>  }<br><br>  const etag = computeEtag(results);<br>  if (maybeNotModified(req, res, etag)) return;<br><br>  res.set(&#39;ETag&#39;, etag);<br>  res.set(&#39;Vary&#39;, &#39;Accept&#39;);<br>  res.set(&#39;Location&#39;, `/contacts/queries/${storeQuery(parsed)}`);<br>  return respondWithResults(req, res, results);<br>}</pre><h3>Testing your endpoint with curl</h3><p>Modern curl lets you send an arbitrary method with -X:</p><p>bash</p><pre># A well-formed QUERY<br>curl -X QUERY https://api.example.com/contacts \<br>  -H &#39;Content-Type: application/x-www-form-urlencoded&#39; \<br>  -H &#39;Accept: application/json&#39; \<br>  --data &#39;select=surname,email&amp;limit=10&#39;<br><br># Missing Content-Type → expect 400<br>curl -X QUERY https://api.example.com/contacts --data &#39;select=surname&#39;<br><br># Unsupported format → expect 415 + Accept-Query<br>curl -X QUERY https://api.example.com/contacts \<br>  -H &#39;Content-Type: application/xml&#39; --data &#39;&lt;q/&gt;&#39; -i<br><br># Discover support → expect Allow + Accept-Query<br>curl -X OPTIONS https://api.example.com/contacts -i</pre><p>Assert on the status codes and on the presence of Accept-Query, ETag, and Location. Those headers are the difference between &quot;technically works&quot; and &quot;correct.&quot;</p><h3>What’s next</h3><ul><li><strong>Part 3 — Calling QUERY from the client.</strong> Using the fetch API, surviving the CORS preflight, feature-detecting server support, and gracefully degrading to POST when QUERY isn&#39;t available.</li><li><strong>Part 4 — Caching strategies in depth.</strong> Body-based cache keys, safe normalization, and getting the most out of the Location/Content-Location pattern.</li><li><strong>Part 5 — Migrating POST-based search endpoints to QUERY</strong> without breaking existing clients.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ebaccf2b95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is the HTTP QUERY Method? The Complete Guide to the Web’s Newest Verb]]></title>
            <link>https://adityakrsingh26.medium.com/what-is-the-http-query-method-the-complete-guide-to-the-webs-newest-verb-82662f937205?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/82662f937205</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 09:41:16 GMT</pubDate>
            <atom:updated>2026-07-05T09:41:16.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fF0Lqb3IzPAZaiNhGuwTg.png" /></figure><p>For roughly three decades, developers who needed to send a non-trivial search to a server faced a genuinely awkward choice.</p><p>You could cram everything into a URL and use GET, or you could stuff the search into a request body and use POST. Neither option was actually designed for the job, and every team that built a search API eventually bumped into the trade-offs.</p><p>As of June 2026, there is finally a purpose-built third option: the <strong>HTTP QUERY method</strong>, standardized in <strong>RFC 10008</strong>. It is, in a sense, the method the web always needed for reading data one that combines the body of a POST with the guarantees of a GET.</p><h3>The short version</h3><p>QUERY is a new HTTP request method that lets a client send a request body like POST while remaining <strong>safe and idempotent</strong> like GET.</p><p>In plain terms: you can send a large, structured search in the request body, and the server <em>and every cache and proxy between you and it</em> understands that the request does not change any state and can be safely repeated, retried, or cached.</p><p>That single property <strong>a body-carrying method</strong> that is nonetheless safe and idempotent is the entire reason QUERY exists.</p><p>It closes a gap that GET and POST have left open since the earliest days of the web.</p><h3>Why GET and POST were never enough</h3><p>To appreciate why a whole new method was warranted, it helps to look closely at exactly where the two familiar methods fall short for search-style requests.</p><h3>The problem with GET</h3><p>GET is the natural home for &quot;fetch me something.&quot; It&#39;s <strong>safe</strong> (it doesn&#39;t change server state), <strong>idempotent</strong> (repeating it has the same effect as doing it once), and its responses are <strong>cacheable</strong>.</p><p>The catch is structural: everything that defines the request has to fit in the URL. That&#39;s perfectly fine for GET /feed?q=foo&amp;limit=10, but it unravels as queries grow:</p><ul><li><strong>URL length isn’t reliably bounded.</strong> A request can pass through many uncoordinated systems (browsers, proxies, gateways, load balancers, CDNs) each with its own limits. There’s no universal maximum you can count on. The HTTP core specification only <em>recommends</em> that senders and recipients support at least 8,000 octets; beyond that, you’re gambling on the weakest link in the chain.</li><li><strong>Some data is genuinely awkward to encode in a URL.</strong> Expressing a nested JSON filter, a full SQL statement, or an XSLT transformation as URL-encoded text is both inefficient and unreadable. You spend bytes on percent-encoding overhead and lose all structure.</li><li><strong>URLs get logged and bookmarked.</strong> Query parameters routinely land in server access logs, browser history, proxy logs, and bookmarks. If your search contains anything sensitive (a customer identifier, a health term, a security filter) <em>the URL is precisely the wrong place to put it</em>.</li><li><strong>Every parameter combination becomes a distinct resource.</strong> Encoding a query into the URL effectively casts each unique combination of inputs as its own URL. That fragments caches, muddies analytics, and inflates the surface area of your API.</li></ul><h3>The problem with POST</h3><p>Faced with those limits, most developers reach for POST, moving the search into the request body:</p><pre>POST /feed HTTP/1.1<br>Host: example.org<br>Content-Type: application/x-www-form-urlencoded<br><br>q=foo&amp;limit=10&amp;sort=-published</pre><p>This solves the <em>size and structure</em> problem but it quietly throws away the <em>guarantees</em> you actually wanted.</p><p>POST is defined as <strong>potentially unsafe</strong> and <strong>potentially non-idempotent</strong>. Crucially, without special, hard-coded knowledge of that specific endpoint, nothing in the request tells any intermediary that this is <em>merely a read</em>.</p><p>The consequences ripple through the whole stack:</p><ul><li><strong>Caches won’t cache the response</strong> the way they would for a read, because they can’t assume the operation is repeatable and side-effect-free.</li><li><strong>Automatic retry logic has to stay conservative.</strong> Retrying a POST after a dropped connection risks double-submitting a real change, so well-behaved clients avoid it even when the POST was really just a search.</li><li><strong>Proxies, gateways, and client libraries can’t optimize.</strong> They must treat the request as a potential mutation.</li></ul><p>In short, you’ve smuggled a read operation inside a method that the entire ecosystem is <strong>obligated to treat as a write</strong>.</p><h3>Where QUERY fits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*F4jlvSz8Jsci4fyz0721RQ.png" /><figcaption>When should I use QUERY?</figcaption></figure><p>QUERY is the method that spans the gap. The very same search becomes:</p><pre>QUERY /feed HTTP/1.1<br>Host: example.org<br>Content-Type: application/x-www-form-urlencoded<br><br>q=foo&amp;limit=10&amp;sort=-published</pre><p>Like POST, the input travels in the request body rather than the URL. Unlike POST, the method is <strong>explicitly safe and idempotent</strong> which means caching and automatic retries are permitted to work normally again, without any special per-endpoint knowledge.</p><p>Here’s how the three methods compare on the properties that matter most.</p><ul><li><strong>GET</strong> is safe, idempotent, and cacheable, and it identifies the query in the URL by definition but it has no defined semantics for a request body, so the whole query must live in the URL.</li><li><strong>POST</strong> carries a request body as expected, but it’s only <em>potentially</em> safe and <em>potentially</em> idempotent, its responses are cacheable only for a subsequent GET or HEAD, and it can’t assign a URI to the query itself.</li><li><strong>QUERY</strong> is the best of both worlds: it’s safe, it’s idempotent, it’s cacheable, it expects a request body, and it can optionally assign a URI both to the query itself (via the Location header) and to the result (via Content-Location).</li></ul><p>The one line that captures the whole story: <strong>QUERY is the only method that carries a body <em>and</em> is safe and idempotent.</strong>That’s the sweet spot.</p><h3>How QUERY works on the wire</h3><p>At its core, a QUERY request asks the target resource to run a query operation and return the result.</p><p>Two ideas do the heavy lifting:</p><ol><li><strong>The request body and its media type together <em>define</em> the query.</strong> The Content-Type isn&#39;t decorative it tells the server how to interpret the body (as form data, SQL, JSONPath, and so on).</li><li><strong>The server determines the scope</strong> of the operation based on the target resource (the path you’re querying).</li></ol><p>Here’s a complete round trip:</p><ul><li><strong>Request:</strong></li></ul><pre>QUERY /contacts HTTP/1.1<br>Host: example.org<br>Content-Type: application/x-www-form-urlencoded<br>Accept: application/json<br><br>select=surname,givenname,email&amp;limit=10&amp;match=%22email=*@example.*%22</pre><ul><li><strong>Response:</strong></li></ul><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br><br>[<br>  { &quot;surname&quot;: &quot;Smith&quot;,   &quot;givenname&quot;: &quot;John&quot;,    &quot;email&quot;: &quot;smith@example.org&quot; },<br>  { &quot;surname&quot;: &quot;Jones&quot;,   &quot;givenname&quot;: &quot;Sally&quot;,   &quot;email&quot;: &quot;sally.jones@example.com&quot; },<br>  { &quot;surname&quot;: &quot;Dubois&quot;,  &quot;givenname&quot;: &quot;Camille&quot;, &quot;email&quot;: &quot;camille.dubois@example.net&quot; }<br>]</pre><p>A few rules shape this behavior, and they’re worth committing to memory:</p><ul><li><strong>Content-Type is mandatory.</strong> A server <em>must</em> reject a QUERY whose Content-Type is missing or inconsistent with the actual body. There is deliberately <strong>no content sniffing</strong> a server is not allowed to guess the format from the bytes and then override a missing or wrong declared type.</li><li><strong>A </strong><strong>200 OK means the results are in the response body.</strong> Any 2xx status signals the request was received, understood, and accepted; 200 specifically means the query ran and its results are enclosed as the response content.</li><li><strong>The query language is not dictated.</strong> The body can be form-encoded, SQL, JSONPath, XSLT, or any media type the server understands. QUERY defines the <em>transport and semantics of the method</em>, not a query syntax.</li></ul><h3>Status codes: what the server tells you</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snER0GDCHzjCvngUDuJy_Q.png" /><figcaption>QUERY request lifecycle &amp; status codes</figcaption></figure><p>Because QUERY hinges on the interplay between the body and its media type, the spec is specific about which error the server should return when something is off. This makes client error-handling predictable:</p><ul><li><strong>200 OK</strong> : the query ran and its results are enclosed in the response body.</li><li><strong>400 Bad Request</strong> : the request is malformed. This covers two cases: no media type was provided (a QUERY without a Content-Type is malformed by definition), or the declared media type doesn&#39;t match the actual body (no sniffing is allowed, so a mismatch is a client error).</li><li><strong>415 Unsupported Media Type</strong> : the media type is understood but not supported on this resource. The server can list acceptable formats via Accept-Query.</li><li><strong>406 Not Acceptable</strong>: the <em>response</em> type the client requested (via Accept) isn&#39;t something the server can produce.</li><li><strong>422 Unprocessable Content</strong> : the request was well-formed and the format was supported, but the <em>content</em> of the query couldn&#39;t be processed. The classic example is syntactically valid SQL that references a non-existent table.</li><li><strong>405 Method Not Allowed</strong> : the resource doesn&#39;t support QUERY at all. The server should include an Allow header listing what it does support.</li></ul><p>The 422 case is a nice illustration of the layering: the request was well-formed <em>and</em> the format was supported, but the <em>content</em> of the query couldn&#39;t be processed against the data.</p><h3>Discovering whether a server supports QUERY</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6YwBhs9WgwYuboSbojUnA.png" /><figcaption>Discovering QUERY support</figcaption></figure><p>Because QUERY is new, clients need a reliable way to find out whether a given resource speaks it. There are two clean approaches.</p><p><strong>1. The </strong><strong>OPTIONS method</strong>, which reports the methods a resource allows:</p><pre>OPTIONS /contacts HTTP/1.1<br>Host: example.org</pre><pre>HTTP/1.1 200 OK<br>Allow: GET, QUERY, OPTIONS, HEAD</pre><p><strong>2. The new </strong><strong>Accept-Query response header</strong>, introduced alongside the method. A resource uses it to advertise both <em>that</em> it supports QUERY and <em>which</em> query-format media types it accepts:</p><pre>HEAD /contacts HTTP/1.1<br>Host: example.org</pre><pre>HTTP/1.1 200 OK<br>Content-Type: application/xhtml<br>Accept-Query: application/x-www-form-urlencoded, application/sql</pre><p>A key subtlety: Accept-Query is a <strong>structured field</strong>. Despite looking similar to the familiar Accept header, it must be parsed according to the HTTP Structured Fields rules, not treated as a plain comma-separated list.</p><p>The order of listed types is not significant, and its value applies to every URL on the server sharing the same path (the query component is ignored for this purpose).</p><p>If a client simply tries a QUERY with an unsupported format, the server responds 415 Unsupported Media Type and can enumerate the formats it <em>does</em> accept.</p><h3>Query formats: SQL, JSONPath, XSLT, and more</h3><p>One of QUERY’s most liberating design choices is that it doesn’t impose a query language. The Content-Type of the body picks the language, and a single resource can support several.</p><p>Here are three flavors against the same conceptual dataset.</p><ul><li><strong>Form-encoded</strong> (the browser-friendly default):</li></ul><pre>QUERY /contacts HTTP/1.1<br>Content-Type: application/x-www-form-urlencoded<br><br>select=surname,givenname,email&amp;limit=10</pre><ul><li><strong>JSONPath</strong> : expressive filtering over JSON data. This request asks for the document IDs of all rejected errata submitted since 2024:</li></ul><pre>QUERY /errata.json HTTP/1.1<br>Content-Type: application/jsonpath<br>Accept: application/json<br><br>$..[<br>     ?@.errata_status_code==&quot;Rejected&quot;<br>     &amp;&amp; @.submit_date&gt;&quot;2024&quot;<br>   ]<br>   [&quot;doc-id&quot;]</pre><ul><li><strong>XSLT</strong> : a full transformation that aggregates and reshapes the data server-side, returning CSV:</li></ul><pre>QUERY /errata.json HTTP/1.1<br>Content-Type: application/xslt+xml<br>Accept: text/csv<br><br>...an XSLT stylesheet describing the transformation...</pre><pre>HTTP/1.1 200 OK<br>Content-Type: text/csv<br>Accept-Query: &quot;application/jsonpath&quot;, &quot;application/xslt+xml&quot;<br><br>year, total, rejected, verified, hdu, reported<br>2020, 387, 68, 117, 123, 79<br>2021, 321, 44, 148, 63, 66<br>2022, 358, 37, 198, 40, 83<br>...</pre><p>The takeaway: QUERY turns “how do I express a rich search over HTTP?” into a content-negotiation problem, which HTTP already knows how to handle well.</p><h3>Reusable results: Location and Content-Location</h3><p>One of QUERY’s more elegant ideas is that a query <em>and</em> its result can each be given their own URL for later reuse with a plain GET. A successful QUERY response can carry either or both of two headers:</p><ul><li><strong>Content-Location</strong> points to a resource holding <em>this specific result set</em>. A client can GET that URL to retrieve the same results again though the server may keep it only temporarily.</li><li><strong>Location</strong> points to a resource representing <em>the query itself</em> (the spec calls this the &quot;equivalent resource&quot;). A GET to that URL re-runs the same operation with the same parameters <strong>without resending the query body</strong> and returns fresh results.</li></ul><p>Here’s a response advertising both:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Content-Location: /contacts/stored-results/17<br>Location: /contacts/stored-queries/42<br>Last-Modified: Sat, 25 Aug 2012 23:34:45 GMT<br><br>[ ...results... ]</pre><p>Now the client has options.</p><p>GET /contacts/stored-results/17 returns the frozen snapshot of results from that query.</p><p>GET /contacts/stored-queries/42 re-executes the query and returns current results — handy when the underlying data changes over time.</p><h3>Conditional requests and the two data-flow patterns</h3><p>The Location pattern shines when combined with conditional requests. Once a query has a stable URL, the client can use validators like ETag and If-None-Match (or If-Modified-Since) to ask &quot;give me the results only if they&#39;ve changed,&quot; and receive a cheap 304 Not Modified when they haven&#39;t.</p><p>The spec describes two data-flow patterns:</p><ul><li><strong>Pattern 1 — QUERY only.</strong> The client keeps sending conditional QUERY requests (with the full body each time). It works, but the body travels on every request, and the server must read the whole body to compute a cache key.</li></ul><pre>Client → QUERY with body            Server → 200 OK, Validator: foo<br>Client → QUERY with body (if foo)   Server → 304 Not Modified<br>        ... data changes ...<br>Client → QUERY with body (if foo)   Server → 200 OK, Validator: bar</pre><ul><li><strong>Pattern 2 — GET to the equivalent resource.</strong> The first QUERY returns a Location. The client then switches to conditional GETs against that URL — no body, smaller requests, and ordinary URL-based caching applies.</li></ul><pre>Client → QUERY with body            Server → 200 OK, Location: /xyz, Validator: foo<br>Client → GET /xyz (if foo)          Server → 304 Not Modified<br>        ... data changes ...<br>Client → GET /xyz (if foo)          Server → 200 OK, Validator: bar</pre><p>Pattern 2 is usually the more efficient long-term shape: pay the cost of the full query once, then poll cheaply.</p><h3>Caching, done right</h3><p>Responses to QUERY are <strong>cacheable</strong> something that was effectively impossible to do cleanly with the POSTworkaround.</p><p>The important twist is that the <strong>cache key must incorporate the request body and its metadata</strong>, not just the URL, because with QUERY the body is what distinguishes one request from another.</p><p>Caches are permitted to <em>normalize</em> the body when computing keys for example, stripping content encodings, or normalizing a +json payload based on knowledge of JSON conventions to improve hit rates.</p><p>But this adds real complexity: a cache has to read the <em>entire</em> body before it can even determine the key, and overly aggressive normalisation risks a false-positive cache hit that returns the wrong result. Clients that want to avoid transformation can send the no-transform cache directive (though it&#39;s advisory).</p><p>This complexity is exactly why the Location-to-GET pattern above is so valuable: once a query has a stable URL, ordinary, well-understood URL-based caching takes over and the body-keying problem disappears for subsequent requests.</p><h3>Redirection</h3><p>QUERY supports the familiar redirect status codes, with one important difference from POST.</p><p>A 301/308 (permanent) or 302/307 (temporary) response means the client should reissue <em>the same QUERY</em> to the new Location the special historical behavior where a POST gets downgraded to a GET after a 301/302 does <strong>not</strong> apply to QUERY.</p><p>A 303 See Other is the exception by design: it tells the client that the query result can be retrieved with a plain GET to the URL in Location. This lets a server respond &quot;indirectly&quot; generating or reusing a result resource and pointing the client at it, rather than returning the body directly.</p><h3>Security considerations</h3><p>QUERY inherits the general security considerations of all HTTP methods, plus a few specifics worth internalizing up front:</p><ul><li><strong>It can keep sensitive data out of URLs.</strong> Because URLs are logged and stored far more readily than request bodies, moving a sensitive search into a QUERY body can be a genuine privacy improvement over GET.</li><li><strong>Temporary result URLs should not leak sensitive input.</strong> If a server mints a Location or Content-Location URL for a query that contained sensitive information, that generated URL should <em>not</em> embed the sensitive portions of the original request.</li><li><strong>Faulty cache normalization is a correctness risk.</strong> A cache that normalizes query bodies incorrectly, or too aggressively, can serve the wrong response on a false-positive match.</li><li><strong>Browsers will send a CORS preflight.</strong> QUERY is not on the CORS “safelist,” so cross-origin browser requests trigger a preflight OPTIONS. Plan for that in any front-end adoption.</li></ul><h3>FAQ</h3><p><strong>Is QUERY a replacement for GET?</strong></p><ul><li>No. For simple reads whose parameters fit comfortably in a URL, GET remains the right tool it&#39;s simpler and universally supported. QUERY earns its place when the query is large, complex, or sensitive.</li></ul><p><strong>Does QUERY change data on the server?</strong></p><ul><li>No. It’s defined as safe: the client neither requests nor expects any change to the target resource’s state. A server <em>may</em> create additional helper resources (like a result URL), but the queried resource itself is untouched.</li></ul><p><strong>Can I use any query language?</strong></p><ul><li>Yes the body’s Content-Type selects the language, and a resource can support several (form data, SQL, JSONPath, XSLT, etc.). Use Accept-Query to discover what a given resource supports.</li></ul><p><strong>Can I use QUERY from a browser today?</strong></p><ul><li>It depends on your runtime and server support, and cross-origin requests will trigger a CORS preflight. We cover client-side usage in detail in Part 3.</li></ul><p><strong>What status code means “your query was fine but returned nothing usable”?</strong></p><ul><li>A syntactically valid query the server can’t fulfill (e.g., referencing a missing table) is 422 Unprocessable Content. An unsupported <em>format</em> is 415; a malformed or type-mismatched request is 400.</li></ul><p><strong>How is caching different from GET?</strong></p><ul><li>The cache key must include the request body and its metadata, not just the URL because the body defines the request. Once a server hands back a Location, clients can switch to GET and lean on normal URL caching.</li></ul><h3>What’s next in this series</h3><p>This pillar established the <em>what</em> and <em>why</em>. The rest of the series gets hands-on:</p><ul><li><strong>Part 2 — Implementing QUERY on the server.</strong> Routing the method, validating Content-Type strictly, choosing correct status codes, and emitting Accept-Query.</li><li><strong>Part 3 — Calling QUERY from the client.</strong> Using the fetch API, handling the CORS preflight, and gracefully degrading when a server doesn&#39;t support the method.</li><li><strong>Part 4 — Caching strategies in depth.</strong> Body-based cache keys, safe normalization, and the Location/Content-Locationresult-reuse pattern.</li><li><strong>Part 5 — Migrating POST-based search endpoints to QUERY</strong> without breaking existing clients.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82662f937205" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Missing Layer Between AI Assistants and Browser DevTools]]></title>
            <link>https://adityakrsingh26.medium.com/the-missing-layer-between-ai-assistants-and-browser-devtools-73cc7cff081f?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/73cc7cff081f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 18:02:38 GMT</pubDate>
            <atom:updated>2026-06-01T18:07:32.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZBt8-DroOBQPhKiU0R9YQ.png" /></figure><p>GitHub: <a href="https://github.com/AdityaKrSingh26/mcp-distill">github.com/AdityaKrSingh26/mcp-distill</a></p><h3>A Browser Already Knows Why Your Button Isn’t Visible</h3><p>A browser already has the answer. It knows:</p><ul><li>The computed styles</li><li>The DOM hierarchy</li><li>The layout tree</li><li>Every console error</li><li>Every failed network request</li><li>Every event listener attached to every element</li></ul><p>Yet AI assistants routinely struggle with debugging tasks that take experienced engineers only seconds.</p><p>The problem is not reasoning capability.</p><p>The problem is <strong>bandwidth</strong>.</p><h3>The Real Bottleneck: Too Much Information</h3><p>Modern Browser MCP (Model Context Protocol) servers expose raw DevTools data directly to LLMs.</p><p>A single CSS inspection may contain:</p><ul><li>Hundreds of computed CSS properties</li><li>Large DOM structures</li><li>Long console logs</li><li>Verbose network traces</li></ul><p>Most of this information is irrelevant to the bug being investigated. The browser has perfect information. The AI has strong reasoning abilities.</p><p>The connection between them is inefficient.</p><h3>Enter: mcp-distill</h3><p>mcp-distill sits between:</p><pre>AI Assistant<br>      ↓<br>mcp-distill<br>      ↓<br>Browser MCP<br>      ↓<br>Chrome DevTools</pre><p>Its job is simple:</p><blockquote>Compress DevTools output into the smallest amount of information that still preserves the signal.</blockquote><h3>The Context Window Is a Scarce Resource</h3><p>Humans and LLMs process information differently.</p><p>Consider a senior engineer inspecting an element with:</p><pre>312 computed CSS properties</pre><p>They do not read all 312. Instead they:</p><ul><li>Scan quickly</li><li>Ignore known defaults</li><li>Look for anomalies</li><li>Narrow attention to a handful of suspicious properties</li></ul><p>Within seconds they might identify:</p><pre>opacity: 0;</pre><p>as the real issue. LLMs cannot do this in the same way.</p><p>Every token consumes attention. Every irrelevant property competes with relevant ones. So instead of focusing on:</p><pre>opacity: 0</pre><p>the model must also process:</p><pre>-webkit-text-stroke-width: 0px<br>animation-delay: 0s<br>backface-visibility: visible<br>...</pre><p>hundreds of times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2As7YB36Av4ma-ts0fkXSg.png" /></figure><p><strong>The signal becomes buried in noise.</strong></p><h3>Why More Context Can Produce Worse Answers</h3><p>A common assumption is:</p><blockquote>More information = Better answers</blockquote><p>For LLMs, that is often false. The actual relationship is:</p><blockquote>Relevant information → Helps<br>Irrelevant information → Hurts</blockquote><p>Research on long-context behaviour consistently shows that models struggle when critical evidence is surrounded by distractors.</p><p>This phenomenon is often called: “<strong><em>Lost in the Middle”</em></strong></p><p>Important information becomes underweighted because attention is spread across too many tokens.</p><h3>Example</h3><p><strong>Scenario A:</strong></p><pre>opacity: 0;</pre><p>Model response:</p><blockquote>The element is invisible because opacity is zero.</blockquote><p><strong>Scenario B:</strong></p><pre>opacity: 0;<br>+ 311 unrelated CSS properties</pre><p>Possible response:</p><blockquote>Maybe z-index is wrong… Perhaps a positioning issue…</blockquote><blockquote>Maybe the container is collapsed…</blockquote><p>The model did not become less capable. The signal-to-noise ratio became worse.</p><h3>Why Prompting Doesn’t Solve This</h3><p>Many people suggest: <strong><em>“Just tell the model to ignore irrelevant properties.”</em></strong></p><p>The issue is that the model must first:</p><ol><li>Read them</li><li>Tokenize them</li><li>Attend to them</li></ol><p>Only then can it decide to ignore them. The filtering must happen <strong>before</strong> the context window. <strong>Not after.</strong></p><h3>One Problem, Three Symptoms</h3><p>The same underlying issue causes:</p><ol><li>Too many tokens : Higher cost</li><li>Too much noise : Lower accuracy</li><li>More context to process : Higher latency</li></ol><p>Reducing noise improves all three simultaneously.</p><h3>What Browser MCPs Actually Do</h3><p>Browser MCP servers expose browser capabilities as tools.</p><p>Examples include:</p><ul><li>Chrome DevTools MCP</li><li>Playwright MCP</li></ul><p>Typical operations:</p><pre>inspect element<br>read console logs<br>execute JavaScript<br>capture screenshots<br>read network activity</pre><p>These tools are designed correctly. They return raw data because they must support many use cases:</p><ul><li>Testing agents</li><li>Accessibility scanners</li><li>Documentation generators</li><li>Debugging assistants</li></ul><p>A general-purpose MCP cannot know what information is important for your task.</p><p>Therefore it returns everything.</p><p>The bandwidth problem appears when that raw output is fed directly into an LLM.</p><h3>Why Build a Proxy Layer?</h3><p>Three possible approaches were considered.</p><h4>Option 1: Replace Browser MCP Entirely</h4><p>Build a brand-new MCP server that talks directly to Chrome DevTools Protocol.</p><p><strong>Advantages</strong></p><ul><li>Complete control</li></ul><p><strong>Disadvantages</strong></p><ul><li>Browser lifecycle management</li><li>CDP maintenance</li><li>Reconnection logic</li><li>Version compatibility</li></ul><p>Large engineering effort with little additional value.</p><h4>Option 2: Extend the MCP Specification</h4><p>Add response-transformation middleware to MCP itself.</p><p><strong>Advantages</strong></p><ul><li>Cleaner architecture</li></ul><p><strong>Disadvantages</strong></p><ul><li>Requires ecosystem adoption</li><li>Slow path to implementation</li></ul><h4>Option 3: Build a Proxy</h4><p>Chosen solution. Architecture:</p><pre>AI Assistant<br>      ↓<br>mcp-distill<br>      ↓<br>Existing Browser MCP<br>      ↓<br>Chrome DevTools</pre><p><strong>Benefits:</strong></p><ul><li>Works immediately</li><li>Compatible with existing MCP servers</li><li>No protocol changes required</li><li>Minimal maintenance burden</li></ul><p><strong>Tradeoffs:</strong></p><ul><li>Extra network hop</li><li>Additional failure point</li><li>Dependency on backend response formats</li></ul><p>These tradeoffs were considered acceptable.</p><h3>Startup Synchronisation Problem</h3><p>The proxy must:</p><ol><li>Register tools immediately</li><li>Connect to the backend MCP asynchronously</li></ol><p>Potential issue:</p><blockquote>Tool call arrives<br>Backend not connected<br>Tool fails</blockquote><p>Solution:</p><pre>await ready;</pre><p>Every tool call waits until the backend connection completes. This eliminates:</p><ul><li>Polling</li><li>Retries</li><li>Startup race conditions</li></ul><p>while keeping tool registration immediate.</p><h3>The Full Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSviKf81vlGTCPF6LMgNHw.png" /></figure><h3>Why Not Use Another LLM for Summarisation?</h3><p>An obvious question: <strong>“<em>Why not pass DevTools output through a smaller model first?”</em></strong></p><p>Several reasons.</p><h4>1. Determinism</h4><p>Heuristics always produce identical output. LLMs may:</p><ul><li>Vary between runs</li><li>Omit details</li><li>Hallucinate information</li></ul><p>Compression must be reliable.</p><h4>2. Latency</h4><p>Heuristics: &lt; <strong>1 millisecond. </strong>LLM summarisation: <strong>1–3 seconds</strong> per tool call.</p><h4>3. Cost</h4><p>No additional API usage. No extra token spend.</p><h4>4. Closed-Domain Problems Favour Rules</h4><p>CSS visibility failures come from a finite set of causes:</p><ul><li>opacity: 0</li><li>display: none</li><li>visibility: hidden</li><li>clip-path</li><li>overflow clipping</li><li>zero dimensions</li></ul><p>Because these failure modes are enumerable, rule-based detection is more reliable than probabilistic summarization.</p><h3>The Compression Pipeline</h3><p>Each tool runs raw DevTools output through a multi-stage pipeline. The stages aren’t just sequential transforms each one makes a specific tradeoff decision about what information is worth preserving. Here’s how it works end to end.</p><h3>diagnose_element : The CSS Problem</h3><h4>Step 1: Extraction</h4><p>The tool calls the backend MCP’s evaluate_script (or equivalent) with an injected JavaScript snippet that runs getComputedStyle() and getBoundingClientRect() on the target selector inside the browser. The raw return is a flat object with every computed CSS property and the element&#39;s position/dimensions.</p><p>For a typical button: ~312 properties, ~4,800 tokens.</p><h4>Step 2: Filtering (the 3-tier system)</h4><p>The first pass cuts the property count by ~95% using a tier classification:</p><pre>// Tier 1: always include — these directly cause visible bugs<br>const TIER1 = new Set([<br>  &quot;display&quot;, &quot;visibility&quot;, &quot;opacity&quot;, &quot;position&quot;, &quot;z-index&quot;,<br>  &quot;width&quot;, &quot;height&quot;, &quot;overflow&quot;, &quot;overflow-x&quot;, &quot;overflow-y&quot;,<br>  &quot;top&quot;, &quot;right&quot;, &quot;bottom&quot;, &quot;left&quot;,<br>  &quot;flex&quot;, &quot;flex-direction&quot;, &quot;flex-grow&quot;, &quot;flex-shrink&quot;, &quot;flex-basis&quot;,<br>  &quot;align-items&quot;, &quot;justify-content&quot;,<br>  &quot;transform&quot;, &quot;clip-path&quot;,<br>  &quot;margin&quot;, &quot;padding&quot;, &quot;border-width&quot;,<br>  &quot;box-sizing&quot;, &quot;pointer-events&quot;,<br>]);<br><br><br>// Tier 2: include only if value is non-default<br>const TIER2 = new Set([<br>  &quot;color&quot;, &quot;background-color&quot;, &quot;background&quot;, &quot;font-size&quot;,<br>  &quot;line-height&quot;, &quot;cursor&quot;, &quot;box-shadow&quot;, &quot;outline&quot;,<br>]);<br>const BORING_TIER2 = new Set([<br>  &quot;rgba(0, 0, 0, 0)&quot;, &quot;transparent&quot;, &quot;none&quot;, &quot;normal&quot;, &quot;auto&quot;,<br>  &quot;rgb(0, 0, 0)&quot;, &quot;0px&quot;, &quot;inherit&quot;, &quot;initial&quot;,<br>]);</pre><p><strong>Tier 1 properties</strong> are always in the output. They cover layout, visibility, positioning, and interactivity the properties that determine whether an element is rendered, where it appears, and whether it can be clicked.</p><p><strong>Tier 2 properties </strong>are only included when their value looks anomalous. background-color: transparent is the default and tells you nothing; background-color: #ffffff might mean the element is covering something behind it.</p><p>Everything else webkit prefixes, SVG-specific properties, CSS custom property resolutions, animation internals is dropped entirely.</p><p>The calibration of Tier 2 matters. The first version of this filter dropped color properties entirely and missed cases like color: transparent (text invisible against background) and background: rgba(0,0,0,0.9) (dark overlay blocking interaction). The anomalous-value check catches those without reopening the floodgates.</p><h4>Step 3: Heuristic analysis (visibility + layout passes)</h4><p>Filtering reduces volume. Heuristics add interpretation. Two analysis passes run over the filtered properties:</p><p><strong>Visibility pass</strong> checks for the orthogonal mechanisms that make elements invisible:</p><ul><li>opacity: 0 (or &lt; 0.1) element exists in layout, may still receive pointer events, is visually invisible. High severity. The fix is usually CSS-based (opacity: 1) or a class removal.</li><li>display: none element is removed from layout entirely, non-interactive. High severity. Different from opacity nothing occupies that space. Fix is usually toggling a class or style.</li><li>visibility: hidden or visibility: collapse invisible and always ignores pointer events regardless of pointer-events property. High severity.</li><li>clip-path with a clipping value element occupies layout space but may be visually clipped to zero area. Medium severity.</li><li>overflow: hidden with zero computed dimensions common container collapse scenario where children are clipped. High severity.</li><li>pointer-events: none element renders correctly but is unclickable. Low severity (not an invisibility bug, but a common interactivity bug that gets confused for one).</li></ul><p>These aren’t variations on the same problem. opacity: 0 vs display: none have different layout effects, different event behavior, and different common causes. Labeling them distinctly saves the model from having to derive those distinctions from raw property values.</p><p><strong>Layout pass</strong> checks for positioning pathologies:</p><ul><li>Zero computed width or height without an explicit width: 0 or height: 0 in styles suggests the element collapsed, often a flex/grid misconfiguration.</li><li>position: absolute or position: fixed without any of top, right, bottom, left set element is positioned but unanchored, may be invisible or offscreen.</li><li>z-index on a position: static element z-index has no effect on statically positioned elements; this is a common CSS misunderstanding.</li></ul><h4>Step 4: Ranking + output</h4><p>Issues are sorted by severity (high → medium → low). The result is a structured object with a plain-language summary and the filtered property set:</p><p><strong>Before</strong> (312 properties, ~4,800 tokens):</p><pre>-webkit-align-content: normal<br>-webkit-align-items: normal<br>-webkit-align-self: auto<br>accent-color: auto<br>appearance: auto<br>aspect-ratio: auto<br>...<br>[308 more properties]</pre><p><strong>After</strong> (8 properties, ~300 tokens):</p><pre>{<br>  &quot;summary&quot;: &quot;#submit-button: opacity:0 (likely cause)&quot;,<br>  &quot;details&quot;: {<br>    &quot;issues&quot;: [<br>      { &quot;type&quot;: &quot;invisible&quot;, &quot;property&quot;: &quot;opacity&quot;, &quot;value&quot;: &quot;0&quot;, &quot;severity&quot;: &quot;high&quot; }<br>    ],<br>    &quot;styles&quot;: {<br>      &quot;display&quot;: &quot;inline-flex&quot;,<br>      &quot;opacity&quot;: &quot;0&quot;,<br>      &quot;position&quot;: &quot;relative&quot;,<br>      &quot;width&quot;: &quot;120px&quot;,<br>      &quot;height&quot;: &quot;40px&quot;,<br>      &quot;pointer-events&quot;: &quot;auto&quot;,<br>      &quot;overflow&quot;: &quot;visible&quot;,<br>      &quot;z-index&quot;: &quot;auto&quot;<br>    }<br>  }<br>}</pre><p>The model receives a labeled diagnosis with supporting evidence. One tool call, one answer.</p><p><strong>Batch mode</strong>: the tool accepts an array of up to 20 selectors and runs all of them in a single evaluate_script call one round-trip regardless of how many elements you&#39;re inspecting. If a selector matches nothing, the response includes &quot;did you mean&quot; suggestions based on similar class names found in the live DOM.</p><h3>get_errors : The Console Noise Problem</h3><h4>Step 1: Extraction</h4><p>The tool calls the backend MCP’s console log endpoint. Different MCPs name this differently (get_console_logs, browser_console_messages, etc.) the tool tries a list of known names and uses the first that succeeds. The raw return is an array of log entries, each with a level, message text, optional source URL, and optional stack trace.</p><p>For a running React app in dev mode: typically 400–1,000 entries, ~10,000–15,000 tokens.</p><h4>Step 2: Noise filtering</h4><p>Before deduplication, a regex allowlist removes entries that are never useful for debugging:</p><pre>const NOISE_PATTERNS = [<br>  /^Warning: Each child in a list should have a unique &quot;key&quot; prop/,<br>  /^Warning: React does not recognize the `\w+` prop on a DOM element/,<br>  /^\[HMR\]/, /^\[vite\]/, /^\[webpack\]/,<br>  /^Download the React DevTools/,<br>  /^Warning: ReactDOM.render is no longer supported/,<br>  /is deprecated and will be removed/i,<br>];</pre><p>These patterns match categories of output that are structurally noise: framework internals, dev tooling prompts, deprecation warnings that don’t indicate a current bug. None of them point to something actionable. Removing them before deduplication keeps the fingerprint map small.</p><h4>Step 3: Deduplication via fingerprinting</h4><p>The same error appearing in a render loop generates hundreds of identical or near-identical entries.</p><p>Deduplication on the raw message string handles exact duplicates, but real errors often contain dynamic values object memory addresses, timestamps, line numbers from minified bundles. Two entries for the same bug look different as strings.</p><p>Fingerprinting normalizes those away:</p><pre>function fingerprint(entry) {<br>  const normalized = (entry.text ?? entry.message ?? &quot;&quot;)<br>    .replace(/0x[0-9a-f]+/gi, &quot;0x?&quot;)          // object addresses<br>    .replace(/:\d+:\d+/g, &quot;:?:?&quot;)              // line:column references<br>    .replace(/\b\d{5,}\b/g, &quot;?&quot;);              // large numeric IDs<br>  return `${entry.level ?? entry.type ?? &quot;log&quot;}::${normalized.slice(0, 200)}`;<br>}</pre><p>Entries that produce the same fingerprint are merged into one, with a count field tracking how many times it occurred. A TypeError that fired 312 times becomes one entry with &quot;count&quot;: 312.</p><h4>Step 4: Ranking</h4><p>After deduplication, entries are sorted by severity rank (error &gt; warning &gt; info/log &gt; debug), then by frequency within each rank. The top N (default: 20) are returned.</p><p>In practice, a typical debugging session has 3–8 unique real errors after noise filtering and deduplication.</p><h4>Step 5: Stack trace compression + source map resolution</h4><p>Raw stack traces include internal frames from node_modules, webpack runtime, React fiber internals none of which point to your code.</p><p>The compression step strips internal frames (matching /node_modules|webpack-internal/) and truncates to the top 3 application frames.</p><p>Then source map resolution runs on any frame that looks minified:</p><p>Before resolution:</p><pre>at ? (dist/app.min.js:1:84729)<br>at t (dist/app.min.js:1:12043)</pre><p>After:</p><pre>at fetchItems (src/components/ProductList.jsx:42:18)<br>at useEffect (src/hooks/useProducts.js:17:4)</pre><p>If resolution fails at any step, the minified frame is kept with a note in _sourcemap_note. The pipeline never discards a frame it either resolves it or preserves it as-is.</p><p><strong>Final output</strong> for 847 raw entries:</p><pre>{<br>  &quot;summary&quot;: &quot;3 unique issues (from 847 total log entries). Top: TypeError: Cannot read properties of undefined&quot;,<br>  &quot;details&quot;: {<br>    &quot;total_log_entries&quot;: 847,<br>    &quot;_sourcemap_resolved&quot;: 2,<br>    &quot;unique_issues&quot;: [<br>      {<br>        &quot;level&quot;: &quot;error&quot;,<br>        &quot;message&quot;: &quot;TypeError: Cannot read properties of undefined (reading &#39;map&#39;)&quot;,<br>        &quot;count&quot;: 312,<br>        &quot;stackTrace&quot;: [<br>          &quot;at fetchItems (src/components/ProductList.jsx:42:18)&quot;,<br>          &quot;at useEffect (src/hooks/useProducts.js:17:4)&quot;<br>        ]<br>      },<br>      {<br>        &quot;level&quot;: &quot;error&quot;,<br>        &quot;message&quot;: &quot;Failed to load resource: net::ERR_CONNECTION_REFUSED&quot;,<br>        &quot;count&quot;: 89,<br>        &quot;source&quot;: &quot;https://api.example.com/products&quot;<br>      },<br>      {<br>        &quot;level&quot;: &quot;warning&quot;,<br>        &quot;message&quot;: &quot;Can&#39;t perform a React state update on an unmounted component&quot;,<br>        &quot;count&quot;: 446,<br>        &quot;stackTrace&quot;: [&quot;at cleanup (src/components/Modal.jsx:88:12)&quot;]<br>      }<br>    ]<br>  }<br>}</pre><p>Three issues, source-mapped stack traces, occurrence counts. The model knows immediately where to look.</p><h3>Failure Modes</h3><p>The honest section.</p><ul><li><strong>False negatives</strong> : a property got filtered out that was actually the bug. This is the most serious failure mode. The mitigation is graceful degradation: if the compression logic throws, the tool returns the raw DevTools output with a _lens_warning field explaining what happened. The AI always gets data; it may just be raw.</li><li><strong>False positives :</strong> something got ranked as high severity that wasn’t the bug. There’s no automatic mitigation here. This is tracked as a known limitation. In practice it’s less harmful than false negatives, since the model can usually reason past a wrong label if the underlying data is correct.</li><li><strong>Backend MCP name mismatches</strong> : different browser MCP servers expose the same operations under different tool names. evaluate_script, execute_javascript, browser_evaluate all do the same thing depending on which MCP you&#39;re using. The defensive routing tries a list of known names before giving up:</li></ul><pre>const EVAL_TOOL_NAMES = [<br>    &quot;evaluate_script&quot;, <br>    &quot;execute_javascript&quot;, <br>    &quot;browser_evaluate&quot;<br>];<br><br>for (const toolName of EVAL_TOOL_NAMES) {<br>  try { <br>      result = await callTool(toolName, args); <br>      break; <br>  }<br>  catch (e) { <br>      if (toolName === EVAL_TOOL_NAMES.at(-1)) <br>        throw e; <br>  }<br>}</pre><ul><li><strong>Missing source maps : </strong>stack traces stay minified. The resolver returns the minified frame rather than failing.</li><li><strong>Selector not found</strong> : diagnose_element on a selector that matches nothing. The tool returns &quot;did you mean&quot; suggestions based on similar selectors found in the DOM, instead of an empty result.</li></ul><h3>Getting Started</h3><p>Example <strong>Claude Code</strong> configuration:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;mcp-distill&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [&quot;mcp-distill&quot;],<br>      &quot;env&quot;: {<br>        &quot;MCP_DISTILL_BACKEND_CMD&quot;: &quot;npx&quot;,<br>        &quot;MCP_DISTILL_BACKEND_ARGS&quot;: &quot;chrome-devtools-mcp&quot;<br>      }<br>    }<br>  }<br>}</pre><p>For <strong>Playwright</strong>:</p><pre>{<br>  &quot;MCP_DISTILL_BACKEND_CMD&quot;: &quot;npx&quot;,<br>  &quot;MCP_DISTILL_BACKEND_ARGS&quot;: &quot;@playwright/mcp&quot;<br>}</pre><p><strong>Available tools</strong>:</p><pre>diagnose_element()<br>get_errors()</pre><p>Requirements:</p><ul><li>Node.js 20+</li><li>@modelcontextprotocol/sdk</li><li>source-map-js</li></ul><h3>Roadmap</h3><h3>v0.2</h3><ul><li>get_network_failures</li><li>inspect_state</li><li>diagnose_form</li><li>accessibility_check</li></ul><h3>Longer-Term</h3><ul><li>Direct CDP integration</li><li>React-aware CSS analysis</li><li>Tailwind understanding</li><li>CSS Modules awareness</li><li>Performance bottleneck detection</li></ul><h3>Closing Thought</h3><p>The most interesting insight behind mcp-distill is that many apparent AI reasoning failures are actually information-management failures.</p><p>Human engineers rarely reason over all available information.</p><p>Instead, they:</p><ol><li>Filter aggressively</li><li>Identify anomalies</li><li>Reduce the search space</li><li>Then reason</li></ol><p>Most AI tooling reverses that order. It sends everything to the model and asks the model to filter afterward. That approach is expensive, slower, and often less accurate.</p><p>The browser does not lack information. The model does not lack reasoning ability. The bottleneck is the interface between them.</p><p>mcp-distill is an attempt to solve that bottleneck by reducing noise before reasoning begins</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73cc7cff081f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Git Stores Years of Code Without Becoming Enormous]]></title>
            <link>https://adityakrsingh26.medium.com/how-git-stores-years-of-code-without-becoming-enormous-09e85b485108?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/09e85b485108</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Sun, 17 May 2026 09:24:28 GMT</pubDate>
            <atom:updated>2026-05-17T09:24:28.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yePzg_JbSoFJMLQP.png" /></figure><p>Most developers use Git every day without thinking much about what happens underneath.</p><p>You edit a file. Run:</p><pre>git add .<br>git commit -m &quot;fix bug&quot;</pre><p>and somehow Git remembers everything forever: every version of every file, every branch, every commit.</p><p>Which raises an obvious question:</p><p>Why doesn’t every Git repository become gigantic?</p><p>If Git stored a full copy of the project for every commit, repositories would explode in size almost immediately. A 100 MB project with 10,000 commits should theoretically consume close to a terabyte of storage.</p><p>But real repositories are nowhere near that.</p><p>If you’ve ever run du -sh .git on an old repository, you&#39;ve probably noticed something strange: the .git directory contains years of history, every commit, branch, and tracked file, yet it&#39;s often the same size as, or even smaller than, a single checkout of the code.</p><p>Intuitively, this seems impossible. A naive version-control system storing full copies per commit would make a 50 MB project with 10,000 commits nearly 500 GB. In practice, the .git directory for a repository that size is often well under 1 GB.</p><h3>First, the Biggest Misconception About Git</h3><p>Before going deeper, we need to clear up one very common misconception:</p><p><em>Git does </em><strong><em>not</em></strong><em> primarily store “diffs.”</em></p><p>People often imagine Git working like this:</p><pre>Version 1 → save only changes<br>Version 2 → save only changes<br>Version 3 → save only changes</pre><p>That is <em>not</em> how Git fundamentally thinks about history. Conceptually, Git stores <strong>snapshots</strong>.</p><p>Every commit represents the complete state of the project at that moment.</p><p>But a Git snapshot is not a full physical copy of every file. Most objects are reused across commits.</p><p>So the real question becomes:<br>If Git stores snapshots, how does it avoid duplicating data?</p><p>The answer lies in Git’s storage model.</p><h3><strong>This post is in two parts.</strong></h3><ol><li>The first half explains <em>what</em> Git stores and <em>why</em> it stays small: the object model, content-addressable storage, deduplication, zlib compression, and delta-compressed packfiles.</li><li>The second half explains <em>how</em> Git actually does its work: what files live in .git, what happens when you run git add and git commit and git checkout, and how branches and tags are implemented (spoiler: branches are one-line text files).</li></ol><h3>Git’s Entire Storage System Is Built Around Four Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZnwrunESGFP3nTwJQ66cQ.png" /></figure><p>Inside .git/objects, everything Git stores is one of four object types:</p><ul><li><strong>blob: </strong>the raw contents of a file. No filename, no permissions, no metadata. Just bytes.</li><li><strong>tree</strong>: represents a directory. A tree maps filenames to blobs and subdirectories to other trees. This is what gives structure to the repository.</li><li><strong>commit</strong>: points to a root tree and stores metadata like parent commits, author, timestamp, and message. Conceptually, a commit says: “Here is the state of the repository at this moment.”</li><li><strong>tag: </strong>an annotated tag pointing to another object, with its own metadata.</li></ul><h3>The Core Trick: Content Addressing</h3><p>This is where Git becomes clever. Every object in Git is identified by the hash of its contents.</p><p>For example:</p><pre>hello.txt → SHA hash</pre><p>If the file content changes even slightly, the hash changes too. But if the content stays identical:</p><pre>same content = same hash</pre><p>That single idea changes everything. Because now Git automatically gets deduplication for free.</p><h3>Git Stores Identical Content Only Once</h3><p>Imagine this situation:</p><h4>Commit 1</h4><pre>app.py<br>README.md</pre><h4>Commit 2</h4><p>Only README.md changes. app.py stays exactly the same. A naive system would duplicate both files again.</p><p>Git does not. Instead:</p><pre>Commit 1<br>├── app.py → Blob A<br>└── README → Blob B<br><br>Commit 2<br>├── app.py → Blob A (reused)<br>└── README → Blob C</pre><p>The unchanged file is simply referenced again. No duplication happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*su1tKCfMwcBYVxMDtYdZFw.png" /></figure><p>This is the biggest reason Git repositories stay small. Most files in most commits do not change.</p><p>Git aggressively reuses existing objects instead of storing duplicates.</p><h3>Even Renames Are Cheap</h3><p>Here’s another surprising detail:</p><p>Git blobs do not know filenames. The filename exists only inside tree objects. That means if you rename:</p><pre>src/app.py</pre><p>to:</p><pre>backend/app.py</pre><p>Git usually does <strong>not</strong> duplicate the file contents. The blob stays exactly the same. Only the tree structure changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkfYwixbm3eWtvRaUvYo7A.png" /></figure><p>This is why large file renames in Git are surprisingly cheap. It also explains something interesting:</p><blockquote><em>Git does not truly “track renames.”</em></blockquote><p>It infers them later by noticing identical blobs appearing in different locations.</p><h3>A worked example: How a commit lays out on disk</h3><p>Let’s trace a tiny repo with three commits.</p><p><strong>Commit 1:</strong> create app.py (100 KB) and README.md (2 KB).</p><p>Git writes:</p><ul><li>1 blob for app.py (~100 KB, compressed)</li><li>1 blob for README.md (~2 KB, compressed)</li><li>1 tree object listing both files (~100 bytes)</li><li>1 commit object pointing to that tree (~200 bytes)</li></ul><p><strong>Commit 2:</strong> edit one line in README.md. app.py is untouched.</p><p>Git writes:</p><ul><li>1 new blob for the modified README.md (~2 KB)</li><li>1 new tree (the blob hash for README changed, so the tree’s content changed, so its hash changes) (~100 bytes)</li><li>1 new commit (~200 bytes)</li></ul><p>It does <strong>not</strong> write a new blob for app.py. The new tree still references the same app.py blob hash from commit 1. Storage cost of commit 2 is roughly 2.3 KB, not 102 KB.</p><p><strong>Commit 3:</strong> rename app.py to src/app.py.</p><p>Git writes:</p><ul><li>1 new tree for src/ containing app.py (~50 bytes)</li><li>1 new root tree containing README.md and the src/ tree (~100 bytes)</li><li>1 new commit (~200 bytes)</li></ul><p>The 100 KB app.py blob is <em>still</em> unchanged and still reused. Storage cost of a rename is a few hundred bytes regardless of file size. Git does not track renames as a first-class operation. It infers them later by noticing identical blob hashes appearing at different paths.</p><p>This is why git mv is functionally just rm + add.</p><h3>What Actually Happens During git add</h3><p>Let’s trace a real Git command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNAEgWYsEmdlKiCpy0ovSQ.png" /></figure><p>When you run:</p><pre>git add hello.txt</pre><p>Git:<br>1. hashes the file contents<br>2. stores the blob in <strong>.git/objects/</strong> if it does not already exist<br>3. updates the index (staging area) to reference that blob</p><h3>So Where Does Compression Happen?</h3><p>So far we only have:</p><ul><li>deduplication</li><li>object reuse</li><li>zlib compression</li></ul><p>That already saves a lot of space. But Git goes further. Eventually Git combines objects into <strong>packfiles</strong>.</p><p>You’ll find them here:</p><pre>.git/objects/pack/</pre><p>This is where Git becomes extremely space efficient.</p><h3>Packfiles: where delta compression happens</h3><p>Deduplication and zlib already save a lot of space, but Git has another optimization: packfiles.</p><p>When you run git gc, git push, or when Git decides there are too many loose objects, it creates a packfile: one .pack file containing many objects plus an .idx index for fast lookup, stored in .git/objects/pack/.</p><p>Unlike loose objects, packfiles can store objects as deltas. If blob B is similar to blob A, Git stores B as “apply these changes to A” instead of storing the full content again.</p><p>Common misconceptions about packfile deltas:</p><ul><li><strong>Deltas are chosen by similarity, not history.</strong> Git groups objects using heuristics and may delta unrelated files if it saves space.</li><li><strong>Newer objects are often the base.</strong> Git optimizes for fast access to recent history, so older objects may be stored as deltas against newer ones.</li><li><strong>Delta chains are limited</strong> (default depth: 50) to avoid expensive reconstruction during reads.</li></ul><h3>Packfile format</h3><p>(Optional deep dive) A packfile looks like this:</p><pre>PACK + version + object count<br>[object 1]<br>[object 2]<br>...<br>20-byte SHA-1 checksum</pre><p>Each object contains:</p><ul><li>A variable-length header encoding type and size</li><li>Either zlib-compressed object data or a delta instruction stream</li></ul><p>Two delta types exist:</p><ul><li>OFS_DELTA: references a base object by offset within the same packfile</li><li>REF_DELTA: references a base object by SHA-1, useful for network transfers and thin packs</li></ul><p>OFS_DELTA is smaller and preferred for on-disk storage.</p><p>The companion .idx file maps object hashes to offsets in the .pack, allowing fast lookups.</p><pre>git verify-pack -v .git/objects/pack/pack-*.idx</pre><p>Example output:</p><pre>3b18e512...  blob   2048   980 12345<br>8b137891...  blob   1024   620 13325 1 of 3b18e512...</pre><p>Columns show hash, type, uncompressed size, packed size, offset, and optionally delta depth and base object.</p><p>The key point: packfile deltas are invisible to Git’s object model. Git still treats commits as full snapshots. Delta compression is only a storage optimization handled internally when objects are read.</p><h3>Git’s Object Store Is Surprisingly Simple</h3><p>One of the most interesting things about Git is how little magic there actually is. Loose objects are literally compressed files stored on disk.</p><p>You can inspect them yourself:</p><pre>git cat-file -p &lt;hash&gt;</pre><p>You can list tree contents:</p><pre>git cat-file -p HEAD^{tree}</pre><p>You can even explore .git/objects manually. Git is not a giant database server. Underneath, it’s mostly:</p><ul><li>files</li><li>hashes</li><li>compression</li><li>references</li></ul><p>That simplicity is part of why Git became so reliable.</p><h3>Inside .git</h3><p>So far we’ve focused on Git’s storage model. Now let’s look at how Git actually operates internally: refs, the index, and the files inside .git</p><p>Run:</p><pre>ls .git</pre><p>Typical output:</p><pre>HEAD  config  hooks/  objects/  refs/  index  logs/<br>packed-refs  ORIG_HEAD  FETCH_HEAD</pre><p>Important parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*kCh-0LCGdYVVE99C" /></figure><p>Important parts:</p><ul><li>refs/ : stores branches and tags as simple text files</li><li>packed-refs : compacted version of many refs</li><li>objects/ : loose objects and packfiles</li><li>index : the staging area</li><li>logs/ : reflog history for recovering moved or lost commits</li><li>config : repository settings</li><li>hooks/ : scripts triggered during Git operations</li><li>ORIG_HEAD, FETCH_HEAD, MERGE_HEAD : temporary refs used during merges, rebases, and fetches</li></ul><p>A key detail: branches are just one-line files.</p><pre>echo &quot;a1b2c3...&quot; &gt; .git/refs/heads/my-branch</pre><p>That alone creates a valid branch. git branch mostly wraps this with validation, which is why branch creation is extremely fast.</p><h3>The index: Git’s staging database</h3><p>.git/index is a binary file tracking:</p><ul><li>Blob hashes for staged files</li><li>File permissions and modes</li><li>Cached filesystem metadata</li><li>Merge conflict stages and flags</li></ul><p>The index serves three purposes:</p><ol><li><strong>Staging area: </strong>git add updates the index. git commit builds commits from the index, not directly from the working tree.</li><li><strong>Status cache: </strong>Git compares cached metadata against the filesystem so git status stays fast.</li><li><strong>Merge tracking: </strong>During conflicts, the index can store multiple versions of the same file.</li></ol><p>Inspect it with:</p><pre>git ls-files --stage</pre><p>Example:</p><pre>100644 8b137891... 0 .gitignore<br>100644 3b18e512... 0 hello.txt</pre><p>The final number is the merge stage. Normal files use stage 0.</p><p>A useful mental model: Git constantly manages three trees:</p><ul><li><strong>HEAD</strong> → last commit</li><li><strong>Index</strong> → next commit</li><li><strong>Working tree</strong> → files on disk</li></ul><p>Most Git commands move data between these three.</p><h3>What Happens During git commit</h3><p>When you run:</p><pre>git commit</pre><p>Git roughly performs these steps:</p><ul><li>Step 1: Build tree objects from the index.</li><li>Step 2: Create a commit object pointing to the root tree.</li><li>Step 3: Store the commit object in .git/objects.</li><li>Step 4: Move the current branch reference to the new commit. That’s fundamentally all a commit is: “<em>a snapshot object plus a moved pointer”</em></li></ul><h3>Why Git Is Fast</h3><p>Git stays fast because several design choices reinforce each other:</p><ul><li>Immutable objects simplify storage and caching</li><li>Content-addressed storage automatically deduplicates data</li><li>Branches are lightweight references</li><li>The index avoids rereading every file during <strong>git status</strong></li><li>Packfiles compress large histories efficiently</li></ul><h3>Where Git Struggles</h3><p>Git is brilliant with source code. But it is not perfect for everything. Large binary files are problematic because:</p><ul><li>they are already compressed</li><li>small edits create entirely new blobs</li><li>delta compression works poorly</li></ul><p>This is why repositories containing:</p><ul><li>videos</li><li>datasets</li><li>Photoshop files</li><li>compiled binaries</li></ul><p>can become huge very quickly. Tools like Git LFS exist to solve this problem.</p><h3>The Bigger Idea Behind Git</h3><p>Git looks like a version control tool on the surface. But underneath, it is really a carefully designed content-addressed storage system. Many modern systems use similar ideas:</p><ul><li>Docker image layers</li><li>build caches</li><li>immutable infrastructure</li><li>deduplicated backups</li><li>distributed object stores</li></ul><p>The core insight is always the same: “<em>immutable content should only be stored once”</em></p><p>Git applies that idea remarkably well. That’s why a repository with years of history can still fit comfortably on your laptop.</p><p>Once you see Git as a content-addressed storage system rather than “<em>just version control</em>,” the .git directory stops feeling mysterious.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09e85b485108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making It Shine: Search, Syntax Highlighting, and the Status Bar]]></title>
            <link>https://adityakrsingh26.medium.com/making-it-shine-search-syntax-highlighting-and-the-status-bar-785a282acb52?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/785a282acb52</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[text-editor]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 19:00:22 GMT</pubDate>
            <atom:updated>2026-03-31T19:00:22.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-i6Pha3i8fQbEvAK" /></figure><p>Your editor works.</p><p>You can open files, move around using Vim motions, edit text, save changes, and even undo. But visually, it still feels primitive. Everything looks the same. There is no search. The status bar barely tells you anything. You cannot even tell what language you are editing.</p><p>At this stage, the editor is functional, but not pleasant to use.</p><p>In this post, we fix that.</p><p>We will add three major features:</p><ul><li>Incremental search with live highlighting</li><li>Regex-based syntax highlighting with a 256-color theme</li><li>A segmented status bar with useful context</li></ul><p>We will also add bracket matching, which becomes easy once the rendering system is flexible.</p><p>All these features may look different, but they share a common idea:<br>they plug into the same rendering pipeline.</p><p>The renderer already walks through each visible line. These features simply modify how each line is displayed before it reaches the terminal.</p><h3>Part A: Search</h3><p>A text editor without search is just a viewer with extra steps.</p><p>We need:</p><ul><li>Forward search using /</li><li>Backward search using ?</li><li>Incremental updates while typing</li><li>Highlighting all matches</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeGK701uCeuoq_G1ASIzDQ.png" /></figure><h3>The Search State</h3><p>We need to track:</p><ul><li>What we are searching for</li><li>Which direction</li><li>Where all matches are</li></ul><pre>enum SearchDirection: FORWARD, BACKWARD<br><br>struct SearchMatch:<br>    row: integer<br>    col_start: integer   // rune index, not byte index<br>    col_end: integer     // rune index<br><br>struct SearchState:<br>    pattern: string<br>    direction: SearchDirection<br>    matches: list of SearchMatch<br>    current_index: integer<br>    active: boolean</pre><p>Each match stores:</p><pre>row<br>col_start<br>col_end</pre><p>Important detail: <em>we store positions in </em><strong><em>rune indices</em></strong><em>, not byte indices.</em></p><p>The rune index distinction matters. If your file contains multibyte UTF-8 characters, byte offset 5 and rune offset 5 might point to different positions. The cursor works in rune offsets, so the matches need to be in rune offsets too.</p><h3>Finding Matches</h3><p>Every time the user types a character, we:</p><ol><li>Scan all lines</li><li>Find occurrences of the pattern</li><li>Convert byte offsets → rune offsets</li><li>Store results</li></ol><p>This is brute force, but fast enough for most files.</p><p>The tricky part is the byte-to-rune conversion. Go’s strings.Index returns byte offsets. The cursor and rendering work in rune offsets. So after finding each match, we convert.</p><pre>function find_all(state, lines):<br>    state.matches = []<br>    if state.pattern is empty: return<br><br>    for row, line in lines:<br>        byte_offset = 0<br>        while true:<br>            idx = find_substring(line[byte_offset:], state.pattern)<br>            if idx &lt; 0: break<br>            byte_start = byte_offset + idx<br>            byte_end = byte_start + byte_length(state.pattern)<br>            // Convert byte offsets to rune offsets<br>            rune_start = count_runes(line[0:byte_start])<br>            rune_end = rune_start + count_runes(state.pattern)<br>            state.matches.append(SearchMatch{row, rune_start, rune_end})<br>            byte_offset = byte_end</pre><p>The inner loop slides a window across each line. After finding a match, we advance byte_offset past it and search for the next one. This finds non-overlapping matches if you search for &quot;aa&quot; in &quot;aaa&quot;, you get one match at position 0, not two.</p><h3>Navigating Matches</h3><ul><li>n → next match</li><li>N → previous match</li><li>Wraps around automatically</li></ul><p>Logic:</p><ul><li>Forward search → first match after cursor</li><li>Backward search → last match before cursor</li></ul><p>NextMatch scans forward through the sorted match list looking for the first match after the current cursor position. If it doesn&#39;t find one, it wraps to index 0.</p><pre>function next_match(state, cursor_row, cursor_col):<br>    if state.matches is empty: return -1<br><br>    if state.direction is FORWARD:<br>        // first match after cursor<br>        for i, match in state.matches:<br>            if match.row &gt; cursor_row:<br>                return i<br>            if match.row == cursor_row and match.col_start &gt; cursor_col:<br>                return i<br>        return 0  // wrap to beginning<br><br>    // backward direction: last match before cursor<br>    for i from end to start in state.matches:<br>        if match.row &lt; cursor_row:<br>            return i<br>        if match.row == cursor_row and match.col_start &lt; cursor_col:<br>            return i<br>    return last_index  // wrap to end</pre><p>PrevMatch does the opposite. If the search direction is forward, it looks backward. If the direction is backward, it looks forward. This way n always means &quot;next in the direction you searched&quot; and N always means &quot;opposite direction.&quot;</p><h3>Highlighting Matches</h3><p>Now comes the tricky part.</p><p>The editor already has syntax highlighting using ANSI escape codes.<br>These codes are invisible but still present in the string.</p><p>So we cannot directly index characters.</p><p>Instead, we:</p><ol><li>Walk through the string byte by byte</li><li>Track visible character positions</li><li>Ignore ANSI sequences</li><li>Apply highlight only on visible positions</li></ol><p>This ensures highlights do not break formatting.</p><pre>function apply_search_highlight(<br>    display_line, <br>    matches, <br>    col_offset, <br>    text_width<br>):<br>    // Build a set of visible positions that need highlighting<br>    highlight_positions = set()<br>    for each match in matches:<br>        for col from match.col_start to match.col_end:<br>            vis_col = col - col_offset<br>            if vis_col &gt;= 0 and vis_col &lt; text_width:<br>                highlight_positions.add(vis_col)<br><br>    if highlight_positions is empty: return display_line<br><br>    // Walk through the string tracking visible position vs ANSI escapes<br>    result = &quot;&quot;<br>    vis_pos = 0<br>    in_escape = false<br>    highlighted = false<br><br>    for each byte in display_line:<br>        if byte == ESC:<br>            if highlighted: result += RESET; highlighted = false<br>            in_escape = true<br>            result += byte<br>            continue<br>        if in_escape:<br>            result += byte<br>            if byte == &#39;m&#39;: in_escape = false<br>            continue<br><br>        // Visible character<br>        if vis_pos in highlight_positions:<br>            if not highlighted:<br>                result += BG_YELLOW + FG_BLACK<br>                highlighted = true<br>        else if highlighted:<br>            result += RESET<br>            highlighted = false<br><br>        result += byte<br>        vis_pos++<br><br>    if highlighted: result += RESET<br>    return result</pre><p>The key insight: ANSI escape sequences start with ESC (byte 0x1b) and end with m. Everything between those bytes is part of the escape code and doesn&#39;t count as a visible character. The vis_pos counter only increments for non-escape bytes.</p><h3>Part B: Syntax Highlighting</h3><p>Without syntax highlighting, code is hard to scan.</p><p>With it:</p><ul><li>Keywords stand out</li><li>Strings are distinct</li><li>Comments fade into the background</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lkw5eVnz9YIktxbwQwSBJQ.png" /></figure><h3>Approach</h3><p>We use <strong>regex-based tokenization</strong>. Each language defines rules like:</p><pre>pattern → token type</pre><p>Example token types:</p><ul><li>Keyword</li><li>String</li><li>Comment</li><li>Number</li><li>Function</li><li>Operator</li></ul><h3>Tokens, Rules, and Languages</h3><pre>enum TokenType: KEYWORD, STRING, COMMENT, NUMBER, FUNCTION, TYPE, OPERATOR, BUILTIN<br><br>struct Token:<br>    type: TokenType<br>    start: integer    // byte position in line<br>    end: integer      // byte position in line<br><br>struct Rule:<br>    pattern: regex<br>    token_type: TokenType<br><br>struct Language:<br>    name: string<br>    rules: list of Rule</pre><p>A Token marks a range in a line and says what kind of thing it is. A Rule pairs a regex with a token type. A Language is a named collection of rules.</p><h3>Language Detection</h3><p>Detect the language from the file extension. Simple switch statement.</p><pre>function detect_language(filename):<br>    ext = get_extension(filename)<br>    switch ext:<br>        &quot;.go&quot;: return go_rules()<br>        &quot;.js&quot;: return javascript_rules()<br>        &quot;.py&quot;: return python_rules()<br>        default: return null</pre><p>For display purposes, we also have a separate function that returns a human-readable name without constructing the full rule set this is what the status bar uses.</p><h3>Defining Language Rules</h3><p>Here’s a subset of the Go rules. The order matters comments need to come before operators so that // is matched as a comment, not two division operators.</p><pre>function go_rules():<br>    return Language{<br>        name: &quot;Go&quot;,<br>        rules: [<br>            // Comments first (before operators, so // wins over /)<br>            Rule{pattern: //.*$/, type: COMMENT},<br>            Rule{pattern: /\/\*.*?\*\//, type: COMMENT},<br><br>            // Strings<br>            Rule{pattern: /`[^`]*`/, type: STRING},           // raw strings<br>            Rule{pattern: /&quot;(?:[^&quot;\\]|\\.)*&quot;/, type: STRING},  // quoted strings<br><br>            // Numbers<br>            Rule{pattern: /\b0[xX][0-9a-fA-F]+\b/, type: NUMBER},<br>            Rule{pattern: /\b\d+\.?\d*([eE][+-]?\d+)?\b/, type: NUMBER},<br><br>            // Keywords<br>            Rule{pattern: /\b(?:func|return|if|else|for|...)\b/, type: KEYWORD},<br><br>            // Function calls (identifier followed by open paren)<br>            Rule{pattern: /\b[a-z_][a-zA-Z0-9_]*\(/, type: FUNCTION},<br><br>            // Operators<br>            Rule{pattern: /[+\-*\/%&amp;|^&lt;&gt;=!:]+/, type: OPERATOR},<br>        ]<br>    }</pre><h3>The Highlight Pipeline</h3><p>For each visible line, the highlighter does four things:</p><ol><li><strong>Tokenize</strong>: run every regex rule against the line, collect all matches as tokens</li><li><strong>Sort</strong>: order tokens by start position, prefer longer matches when two start at the same spot</li><li><strong>Remove overlaps</strong>: walk through sorted tokens, skip any that overlap with the previous one</li><li><strong>Colorize</strong>: walk through the line, insert ANSI color codes around each token</li></ol><pre>function highlight(line):<br>    tokens = tokenize(line)<br>    if tokens is empty: return line<br><br>    result = &quot;&quot;<br>    pos = 0<br>    for each token in tokens:<br>        // text before this token (no color)<br>        result += line[pos:token.start]<br>        // the token itself (with color)<br>        result += color_code(token.type) + line[token.start:token.end] + RESET<br>        pos = token.end<br>    // remaining text after last token<br>    result += line[pos:]<br>    return result</pre><h3>Overlap Removal</h3><p>Multiple regex rules will match overlapping regions. The keyword rule matches func. The function call rule matches funcName(. If funcName starts at position 0, both rules produce tokens that overlap.</p><p>The fix is simple. After sorting by start position (longest match first at each position), walk through the list. If a token starts before the previous token ended, skip it.</p><pre>function remove_overlaps(tokens):<br>    result = []<br>    last_end = 0<br>    for each token in tokens:  // already sorted by start position<br>        if token.start &lt; last_end:<br>            continue   // overlaps with previous, skip<br>        result.append(token)<br>        last_end = token.end<br>    return result</pre><p>Because we sort longer matches first at the same start position, the first token at any position is always the longest one. Subsequent overlapping tokens get dropped. This means comments (which tend to be long, spanning to end of line) always win over operators or keywords that might match inside them.<br>Handling Horizontal Scrolling</p><p>There’s a subtle problem. The highlighter produces a string full of ANSI escape codes. But if the user has scrolled the viewport to the right, we need to show only the visible portion of that string. We can’t just slice by byte index — that would cut ANSI codes in half, producing garbage.</p><p>The extractVisiblePortion function walks through the highlighted string, tracking two counters: the current visible character position and the number of visible characters written to the output. It skips characters before the column offset, copies characters within the visible window, and carries forward any active ANSI color code so the first visible character has the right color.</p><pre>function extract_visible_portion(highlighted, col_offset, width):<br>    result = &quot;&quot;<br>    vis_pos = 0<br>    vis_written = 0<br>    in_escape = false<br>    active_color = &quot;&quot;<br><br>    for each byte in highlighted:<br>        if byte == ESC:<br>            in_escape = true<br>            if vis_pos &lt; col_offset:<br>                active_color = reset; active_color += byte<br>            else if vis_written &lt; width:<br>                result += byte<br>            continue<br><br>        if in_escape:<br>            // same routing as ESC byte<br>            if byte == &#39;m&#39;: in_escape = false<br>            continue<br><br>        // visible character<br>        if vis_pos &gt;= col_offset and vis_written &lt; width:<br>            if vis_written == 0 and active_color is not empty:<br>                result = active_color + result<br>            result += byte<br>            vis_written++<br>        vis_pos++<br><br>        if vis_written &gt;= width: break<br><br>    return result</pre><p>The active_color buffer captures the last ANSI code seen before the visible region starts. When we begin writing visible characters, we prepend it. This way, if the visible region starts in the middle of a syntax-highlighted token, it still gets the right color.</p><h3>The ColorTheme Struct</h3><p>There’s an architectural issue. The theme lives in the ui package. The highlighter lives in the syntax package. The highlighter needs color values to produce ANSI codes, but importing ui from syntax would create a circular dependency.</p><p>The solution is a separate ColorTheme struct in the syntax package that holds just the color indices the highlighter needs. The renderer creates one from its theme and passes it when constructing the highlighter.</p><pre>// In syntax package — no dependency on ui<br>struct ColorTheme:<br>    keyword: integer<br>    string: integer<br>    comment: integer<br>    number: integer<br>    function: integer<br>    type: integer<br>    operator: integer<br>    builtin: integer</pre><p>The renderer wires it up:</p><pre>function set_language(file_path):<br>    lang = detect_language(file_path)<br>    if lang is not null:<br>        color_theme = ColorTheme{<br>            keyword:  theme.keyword,<br>            string:   theme.string,<br>            comment:  theme.comment,<br>            ...<br>        }<br>        highlighter = new_highlighter(lang, color_theme)</pre><p>This keeps the dependency one-directional: ui knows about syntax, but syntax doesn&#39;t know about ui.</p><h3>Part C: Status Bar and Theme</h3><p>The status bar gives context at a glance.</p><p>We design it as <strong>segmented blocks</strong>:</p><pre>[ MODE ] [ FILE ] [ LANGUAGE ]        [ POSITION ]</pre><h3>Segmented Design</h3><pre>┌──────────┬──────────────┬──────┬─────────────────┬──────────┐<br>│ ◆ NORMAL │ main.go [+]  │  Go  │                 │ 42,7 65% │<br>└──────────┴──────────────┴──────┴─────────────────┴──────────┘<br>  mode bg     file bg       lang    padding (file bg)  pos bg</pre><p>Each segment uses a different 256-color background. The mode segment is deep blue. The file segment is dark gray. The language segment is slightly lighter gray. The position segment is medium gray. The foreground is bright white throughout.</p><h3>What It Shows</h3><ul><li>Mode (NORMAL, INSERT, SEARCH)</li><li>File name</li><li>Modified indicator [+]</li><li>Language</li><li>Cursor position (row, col)</li><li>File percentage</li></ul><h3>Layout Logic</h3><p>Steps:</p><ol><li>Render left segments (mode + file)</li><li>Optionally render language</li><li>Add padding</li><li>Right-align position</li></ol><p>Important detail:<br>we calculate <strong>visible length</strong>, ignoring ANSI codes.</p><p>Otherwise alignment breaks.</p><pre>function enhanced_status_bar(<br>    theme, <br>    mode, <br>    filename, <br>    modified, <br>    row, <br>    col, <br>    percent, <br>    width<br>):<br>    result = &quot;&quot;<br><br>    // Mode segment<br>    icon = mode_icon(mode)<br>    mode_text = &quot; &quot; + icon + &quot; &quot; + uppercase(mode) + &quot; &quot;<br>    result += bg_color(theme.mode_bg) + fg_color(theme.fg) + bold + mode_text + reset<br><br>    // File segment<br>    display_name = basename(filename) or &quot;[No Name]&quot;<br>    mod_indicator = &quot; [+]&quot; if modified else &quot;&quot;<br>    file_text = &quot; &quot; + display_name + mod_indicator + &quot; &quot;<br>    result += bg_color(theme.file_bg) + fg_color(theme.fg) + file_text + reset<br><br>    // Language segment (if there&#39;s room)<br>    lang = detect_language_name(filename)<br>    if lang is not empty and there&#39;s space:<br>        lang_text = &quot; &quot; + lang + &quot; &quot;<br>        result += bg_color(theme.lang_bg) + fg_color(theme.fg) + lang_text + reset<br><br>    // Padding to push position segment to the right<br>    result += bg_color(theme.file_bg) + spaces_to_fill + reset<br><br>    // Position segment (right-aligned)<br>    pos_text = &quot; row,col  percent% &quot;<br>    result += bg_color(theme.pos_bg) + fg_color(theme.fg) + pos_text + reset<br><br>    return result</pre><h3>The 256-Color Theme</h3><p>The theme defines every color in the editor as a 256-color index. 256-color mode is supported by virtually every modern terminal.</p><p>You set colors with ANSI codes like \x1b[38;5;204m for foreground color 204 and \x1b[48;5;24m for background color 24.</p><pre>struct Theme:<br>    // Syntax colors<br>    keyword: 204           // bright pink, bold<br>    string: 114            // light green<br>    comment: 243           // dim gray, italic<br>    number: 215            // peach/orange<br>    function: 117          // sky blue<br>    type: 141              // purple<br>    operator: 208          // orange<br>    builtin: 216           // light peach<br><br>    // UI colors<br>    line_number: 240       // dark gray<br>    current_line_number: 220  // golden yellow, bold<br>    empty_line: 239        // tilde color<br>    border: 238            // border elements<br><br>    // Status bar segments<br>    status_mode_bg: 24     // deep blue<br>    status_file_bg: 236    // dark gray<br>    status_lang_bg: 238    // slightly lighter gray<br>    status_pos_bg: 240     // medium gray<br>    status_fg: 255         // bright white<br><br>    // Search and brackets<br>    search_highlight: 226  // yellow background<br>    bracket_match: 240     // gray background</pre><h3>Bracket Matching</h3><p>A small feature with big impact.</p><p>When the cursor is on: (, [, { or their closing pairs</p><p>We highlight the matching bracket.</p><p><strong>The algorithm</strong>: check if the character under the cursor is a bracket. If it’s an opening bracket, scan forward with a depth counter. If it’s a closing bracket, scan backward. Increment depth on the bracket type you started from, decrement on its pair. When depth hits zero, you found the match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dbk_oJDZOSpZitChBC6ihw.png" /></figure><pre>function find_matching_bracket(lines, row, col):<br>    char = rune_at(lines[row], col)<br>    for each pair in [(, ), [, ], {, }]:<br>        if char == pair.open:<br>            return scan_forward(lines, row, col, pair.open, pair.close)<br>        if char == pair.close:<br>            return scan_backward(lines, row, col, pair.close, pair.open)<br>    return null<br><br>function scan_forward(lines, start_row, start_col, open, close):<br>    depth = 0<br>    for row from start_row to end:<br>        start_c = start_col if row == start_row else 0<br>        for col from start_c to end of line:<br>            char = rune_at(lines[row], col)<br>            if char == open: depth++<br>            if char == close: depth--<br>            if depth == 0: return {row, col}<br>    return null</pre><p>The backward scan is the mirror image start from the cursor position and work left and up, using the same depth counter logic.</p><p>The bracket match position gets passed to the renderer just like search matches. The renderer applies a gray background to that single character position, using the same ANSI-aware character walking that search highlighting uses.</p><p>This is what I meant at the start about these features sharing a pattern. The renderer’s renderBuffer method calls syntax highlighting first, then applies search highlighting on top, then applies bracket highlighting on top of that. Three independent features, one rendering pipeline.</p><h3>What You Built</h3><p>This post covered four features:</p><ul><li><strong>Incremental search: </strong>/ for forward, ? for backward, with match highlighting across the entire file and n/Nnavigation with wraparound.</li><li><strong>Syntax highlighting: </strong>regex-based tokenization with overlap removal, applied per visible line, with a ColorTheme struct to avoid import cycles.</li><li><strong>Segmented status bar:</strong> mode, filename, language, and position in their own colored segments, with visible-length calculations that account for ANSI codes.</li><li><strong>Bracket matching: </strong>depth-counting scan that finds the matching (), [], or {} and highlights it in the render pipeline.</li><li><strong>256-color theme system: </strong>a single Theme struct that defines every color in the editor, from syntax tokens to status bar segments.</li></ul><p>You started this series by entering raw mode and reading a single byte. Now you have a full modal text editor with syntax highlighting, search, undo, and composable Vim commands.</p><p>There’s nothing magic about any of this. A terminal is a grid. A keystroke is a byte. A text buffer is an array of strings. A syntax highlighter is a list of regexes. An undo system is two stacks. Every tool you use daily is built from pieces this simple. Now you know how they fit together.</p><p><strong>Now you have something that looks like this :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QbyfHVNGtRolqAhZ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VinC-ypO8qlFQpZy" /></figure><p><strong>Previous:</strong></p><ul><li><a href="https://adityakrsingh26.medium.com/i-mass-deleted-a-production-config-and-nano-couldnt-save-me-4357f13badfb"><strong>Post 0 — I Mass-Deleted a Production Config and nano Couldn’t Save Me</strong></a></li><li><a href="https://adityakrsingh26.medium.com/taking-over-the-terminal-raw-mode-and-escape-codes-4ad4aac06943"><strong>Post 1 — Taking Over the Terminal: Raw Mode and Escape Codes</strong></a></li><li><a href="https://adityakrsingh26.medium.com/decoding-the-keyboard-why-your-arrow-keys-send-three-bytes-e9eb95a0ec6e"><strong>Post 2 — Decoding the Keyboard: Why Your Arrow Keys Send Three Bytes</strong></a></li><li><a href="https://adityakrsingh26.medium.com/storing-text-without-losing-your-mind-or-your-unicode-21dc6deb9565"><strong>Post 3 — Storing Text Without Losing Your Mind (or Your Unicode)</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/painting-pixels-in-a-world-made-of-characters-e18e21ba357d"><strong>Post 4 — Painting Pixels in a World Made of Characters</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/the-state-machine-that-makes-modal-editing-click-57c817199da4"><strong>Post 5 — The State Machine That Makes Modal Editing Click</strong></a></li><li><a href="https://adityakrsingh26.medium.com/3dd-and-the-algebra-of-vim-commands-f0964b80bdfe?postPublishedType=repub"><strong>Post 6–3dd and the Algebra of Vim Commands</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/time-travel-building-undo-that-actually-works-4197a6a577d2"><strong>Post 7 — Time Travel: Building Undo That Actually Works</strong></a></li></ul><p>GitHub : <a href="https://github.com/AdityaKrSingh26/Glime"><strong>github.com/AdityaKrSingh26/Glime</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785a282acb52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Travel: Building Undo That Actually Works]]></title>
            <link>https://adityakrsingh26.medium.com/time-travel-building-undo-that-actually-works-4197a6a577d2?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/4197a6a577d2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 04:31:00 GMT</pubDate>
            <atom:updated>2026-03-31T19:01:07.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t--tNSh_EnAUoB6q2kA-ww.png" /></figure><p>Press u in Vim and something strange happens.</p><p>Not one character disappears. Not the last key you pressed.<br>An entire thought vanishes.</p><p>A full sentence you just typed is gone.<br>Press u again, and a line you deleted ten minutes ago comes back.</p><p>Somehow, Vim knows that dozens of keystrokes belong to a single action.</p><p>That’s not magic.</p><p>It’s grouping.</p><p>Underneath that grouping is a simple idea:<br><strong>record what changed, and replay it in reverse.</strong></p><p>Let’s build that.</p><h3>The Naive Approach (and Why It Breaks)</h3><p>The most obvious solution is: “<em>Save the entire file after every change.”</em></p><p>Undo = load the previous snapshot.</p><p>This works. Until it doesn’t.</p><h4>The problem:</h4><ul><li>File size: 100 KB</li><li>Edits: 500</li><li>Storage: <strong>50 MB</strong></li></ul><p>And most of those snapshots differ by just one character.</p><p>You can optimize with diffs, but now you’re building a diff engine just for undo. There’s a simpler approach.</p><h3>Record Actions, Not State</h3><p>Instead of storing the whole file, store <strong>what changed</strong>.</p><p>Example: <em>“Inserted </em><em>x at row 5, column 12”</em></p><p>This tiny record is enough to undo the change: <em>“Delete character at row 5, column 12”</em></p><p>This is the <strong>action-based model</strong>.</p><h3>Actions: The Atoms of Undo</h3><p>Every edit in your editor reduces to a small set of operations:</p><ul><li>Insert character</li><li>Delete character</li><li>Split line</li><li>Join lines</li><li>Insert line</li><li>Delete line</li><li>Replace line</li></ul><p>Each mutation gets recorded as an Action:</p><pre>enum ActionType:<br>    INSERT_CHAR<br>    DELETE_CHAR<br>    SPLIT_LINE<br>    JOIN_LINES<br>    DELETE_LINE<br>    INSERT_LINE<br>    SET_LINE<br><br>struct Action:<br>    type: ActionType<br>    row: integer<br>    col: integer<br>    text: string         // the text involved (char inserted, line content)<br>    prev_text: string    // previous text (for reversal)<br>    cursor_row: integer  // cursor position before the action<br>    cursor_col: integer</pre><h4>Why text and prev_text both exist</h4><p>You need to go <strong>both directions</strong>:</p><ul><li>Forward (redo)</li><li>Backward (undo)</li></ul><p>Examples:</p><ul><li>Insert → store inserted char (text)</li><li>Delete → store deleted char (text)</li><li>Replace → store both new (text) and old (prev_text)</li></ul><h4>Why cursor position matters</h4><p>Undo should restore <strong>context</strong>, not just text.</p><p>Without cursor tracking:</p><ul><li>Text is correct</li><li>Cursor feels random</li></ul><p>That breaks usability.</p><h4>The Real Trick: Grouping</h4><p>If every keystroke is separate, undo becomes painful:</p><ul><li>Type 10 characters → press u 10 times</li></ul><p>That’s not how Vim works.</p><p>Instead: <em>Everything typed in insert mode = </em><strong><em>one undo unit</em></strong></p><h3>Action Groups: Making 47 Keystrokes One “Thing”</h3><p>Actions alone aren’t enough. If every character insertion is a separate undo step, pressing u after typing a sentence would delete one character. That&#39;s what you&#39;d get in Notepad. Vim does something smarter.</p><p>When you press i to enter insert mode, everything you type until you press ESC is one undo unit. One press of u reverses the entire insert session. The trick is grouping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMj5dXG1OTImZCnBG9CDjQ.png" /></figure><p>An ActionGroup is a list of Actions that get undone together:</p><pre>struct ActionGroup:<br>    actions: list of Action</pre><p>The UndoManager holds stacks of these groups and tracks whether a group is currently being built:</p><pre>struct UndoManager:<br>    undo_stack: list of ActionGroup<br>    redo_stack: list of ActionGroup<br>    current: ActionGroup or null<br>    max_size: integer</pre><p>When the user enters insert mode, you call begin_group(). This creates a new empty group:</p><pre>function begin_group(mgr):<br>    mgr.current = new ActionGroup with empty actions list</pre><p>Every character the user types adds an Action to the current group. When they press ESC to leave insert mode, you call end_group():</p><pre>function end_group(mgr):<br>    if mgr.current is null or mgr.current.actions is empty:<br>        mgr.current = null<br>        return<br>    push mgr.current onto mgr.undo_stack<br>    if length(undo_stack) &gt; max_size:<br>        remove oldest entry<br>    mgr.current = null</pre><p>If the user entered insert mode and immediately pressed ESC without typing anything, the group is empty and gets thrown away. No empty groups on the stack.</p><p>The max_size cap prevents the undo stack from growing forever. When you exceed it, the oldest group falls off. In our editor we set this to 1000, which means you can undo the last 1000 distinct operations. That&#39;s plenty for any editing session.</p><p>The record function is what individual edit operations call. It either appends to the current group or creates a standalone single-action group:</p><pre>function record(mgr, action):<br>    // any new edit destroys redo history<br>    clear mgr.redo_stack<br><br>    if mgr.current is not null:<br>        append action to mgr.current.actions<br>        return<br><br>    // auto-wrap in a single-action group<br>    push ActionGroup([action]) onto mgr.undo_stack<br>    if length(undo_stack) &gt; max_size:<br>        remove oldest entry</pre><p>The auto-wrap is important. Commands in normal mode like dd to delete a line or x to delete a character don&#39;t call begin_group() and end_group() explicitly. They just call record(). The manager wraps the action in its own group automatically. One dd becomes one undo step.</p><p>Some normal-mode commands <em>do</em> use explicit groups. Deleting 3 lines with 3dd records three separate DELETE_LINEactions inside one group so that pressing u restores all three lines at once. The paste command groups all its actions too. Any command that makes multiple buffer changes for a single user action needs a group.</p><h3>Dual Stack Model (Undo + Redo)</h3><p>Undo/redo behaves like browser navigation.</p><h4>Undo:</h4><ul><li>Pop from undo stack</li><li>Push to redo stack</li></ul><h4>Redo:</h4><ul><li>Pop from redo stack</li><li>Push back to undo stack</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d4PSEisuP3dRIVeto7Pxdw.png" /></figure><p>Two stacks, and groups shuttle between them.</p><pre>function undo(mgr):<br>    if undo_stack is empty: return null<br>    // finalize any active group first<br>    if mgr.current is not null:<br>        end_group(mgr)<br>    group = pop from undo_stack<br>    push group onto redo_stack<br>    return group<br><br>function redo(mgr):<br>    if redo_stack is empty: return null<br>    group = pop from redo_stack<br>    push group onto undo_stack<br>    return group</pre><p>There’s a subtlety in undo: if the user is in the middle of typing (a group is active), you finalize it before undoing. Otherwise the half-finished group would be lost. This handles the case where someone is typing, realizes they want to undo something earlier, and presses ESC then u. The ESC call end_group(), but even if it didn&#39;t, the undo function would finalize it.</p><h3>Redo Invalidation</h3><p>If you undo, then make a new edit: “<em>The old future is gone.”</em></p><p>Redo stack must be cleared.</p><p>Otherwise you apply changes to a diverged state → corruption.</p><p>Notice the first line of record():</p><pre>clear mgr.redo_stack</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzY67XUHKnqX48X9S5K3xg.png" /></figure><p>Any new edit wipes out the redo history. Here’s why.</p><p>Say you’re in state A. You type “hello” and reach state B. You undo back to state A. The redo stack now holds the path from A to B.</p><p>Now you type “goodbye” instead. You’re now in state C. The redo stack still holds the path to state B but state B no longer makes sense. The buffer has diverged. “Redo” would try to replay the insertion of “hello” on top of text that now says “goodbye.” The result would be garbage.</p><p>So any new edit clears the redo stack. Once you’ve branched off in a new direction, there’s no going forward to the old future.</p><h3>Inverse Operations: Undo Basics</h3><p>Each action has a direct inverse:</p><ul><li>INSERT_CHAR → delete it</li><li>DELETE_CHAR → insert it back</li><li>SPLIT_LINE → restore original line, delete new line</li><li>JOIN_LINES → split back into two</li><li>DELETE_LINE → insert it back</li><li>INSERT_LINE → delete it</li><li>SET_LINE → restore previous text</li></ul><p>This works because each action stores both current (text) and previous (prev_text) states.</p><pre>function apply_inverse(action):<br>   switch action.type:<br>      INSERT_CHAR: buffer.delete_char(action.row, action.col)<br>      DELETE_CHAR: buffer.insert_char(action.row, action.col, action.text[0])<br>      SPLIT_LINE:<br>        buffer.set_line(action.row, action.prev_text)<br>        buffer.delete_line(action.row + 1)<br>     JOIN_LINES:<br>        buffer.set_line(action.row, action.text)<br>        buffer.insert_line(action.row + 1, action.prev_text)<br>     DELETE_LINE: buffer.insert_line(action.row, action.text)<br>     INSERT_LINE: buffer.delete_line(action.row)<br>     SET_LINE: buffer.set_line(action.row, action.prev_text)</pre><p><strong>Key idea:</strong> some inverses need multiple steps.<br>Example: undoing a split requires restoring the original line and removing the extra one.</p><p><strong>Split and join are duals:</strong></p><ul><li>Split → undo behaves like join</li><li>Join → undo behaves like split</li></ul><h4>Undo in the Editor</h4><pre>function editor_undo():<br>    group = undo_manager.undo()<br>    if group is null:<br>        show_message(&quot;Already at oldest change&quot;)<br>        return<br><br>    // reverse order matters<br>    for i = length(group.actions)-1 down to 0:<br>        apply_inverse(group.actions[i])<br><br>    cursor.move_to(group.actions[0].cursor_row,<br>                   group.actions[0].cursor_col)</pre><ul><li>Actions must be undone in <strong>reverse order</strong> to avoid position shifts</li><li>Cursor returns to where the group started</li></ul><h4>Redo</h4><pre>function editor_redo():<br>    group = undo_manager.redo()<br>    if group is null:<br>        show_message(&quot;Already at newest change&quot;)<br>        return<br><br>    for each action in group.actions:<br>        apply_forward(action)<br><br>    cursor.move_to(last_action.cursor_row,<br>                   last_action.cursor_col)</pre><ul><li>Redo applies actions <strong>forward</strong></li><li>Cursor moves to the final state of the group</li></ul><h3>Undo-Aware Wrapper Methods</h3><p>Every text change goes through a wrapper that <strong>records the action before mutating the buffer</strong>.</p><h4>Insert Character</h4><pre>function editor_insert_char(row, col, char):<br>    record(Action{<br>        type: INSERT_CHAR,<br>        row: row, col: col,<br>        text: char,<br>        cursor_row: row, cursor_col: col<br>    })<br>    buffer.insert_char(row, col, char)</pre><h4>Split Line</h4><pre>function editor_split_line(row, col):<br>    original_line = buffer.get_line(row)<br>    record(Action{<br>        type: SPLIT_LINE,<br>        row: row, col: col,<br>        prev_text: original_line,<br>        cursor_row: row, cursor_col: col<br>    })<br>    buffer.split_line(row, col)</pre><h4>Join Lines</h4><pre>function editor_join_lines(row):<br>    line_a = buffer.get_line(row)<br>    line_b = buffer.get_line(row + 1)<br>    record(Action{<br>        type: JOIN_LINES,<br>        row: row,<br>        text: line_a,<br>        prev_text: line_b,<br>        cursor_row: cursor.row, cursor_col: cursor.col<br>    })<br>    buffer.join_lines(row)</pre><h4>Core Pattern</h4><p>All editor mutations follow this:</p><ol><li>Capture any state needed to undo</li><li>Record the action</li><li>Apply the buffer change</li></ol><p>The buffer itself is unaware of undo. It only performs changes.<br>Undo logic exists entirely in the editor layer.</p><h3>Separation of Concerns</h3><p>Clean architecture:</p><ul><li><strong>Buffer</strong>: stores text</li><li><strong>Undo Manager:</strong> manages history</li><li><strong>Editor:</strong> connects both</li></ul><h4>Why this matters</h4><ul><li>Buffer stays simple</li><li>Undo logic stays isolated</li><li>Easy to extend</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz48R0yfYUIozX09qn_3pw.png" /></figure><h3>Wiring It Into Mode Transitions</h3><p>The last piece is connecting groups to mode transitions. When the user enters insert mode via i, a, A, o, or O, the editor calls BeginGroup(). When they press ESC to return to normal mode, it calls EndGroup().</p><p>In pseudocode:</p><pre>on &#39;i&#39; in normal mode:<br>    begin_group()<br>    switch to insert mode<br><br>on ESC in insert mode:<br>    end_group()<br>    switch to normal mode</pre><p>The o and O commands are slightly different. They need to insert a blank line <em>before</em> switching to insert mode. So they call begin_group(), record the line insertion, then switch modes. The blank line and all subsequent typing end up in the same group:</p><pre>on &#39;o&#39; in normal mode:<br>    begin_group()<br>    record INSERT_LINE at row+1<br>    buffer.insert_line(row+1)<br>    move cursor to row+1<br>    switch to insert mode<br>    // user types... each char adds to the same group<br>    // ESC calls end_group()</pre><p>Now u after o undoes the entire thing: the new line and everything typed on it.</p><h3>What You Built</h3><p>Here’s what the undo system gives you:</p><ul><li><strong>Action recording.</strong> Every buffer mutation becomes a small struct with enough data to reverse it. No snapshots, no diffs, no copies of the whole file.</li><li><strong>Grouped undo.</strong> An insert session (enter insert mode, type, leave insert mode) is one undo unit. Multi-action commands like 3dd or paste are also single units. The user&#39;s mental model of &quot;one action&quot; maps to one press of u.</li><li><strong>Dual-stack undo/redo.</strong> Groups move between the undo and redo stacks. Undo pops from one and pushes to the other. Redo does the reverse. New edits clear the redo stack because the old future no longer applies.</li><li><strong>Inverse operations for every action type.</strong> Insert undoes to delete. Split undoes to join. Every action has a clean reverse, and groups are undone in reverse order so row numbers stay correct.</li><li><strong>Separation of concerns.</strong> The buffer doesn’t know about undo. The undo manager doesn’t know about the buffer. The editor sits between them, recording actions through wrapper methods and applying inverses when the user presses u.</li></ul><h3>What’s Next ?</h3><p><strong>Next</strong> <a href="https://medium.com/p/785a282acb52?postPublishedType=initial"><strong>Post 8–Making It Shine: Search, Syntax, and the Status Bar</strong></a></p><p><strong>Previous:</strong></p><ul><li><a href="https://adityakrsingh26.medium.com/i-mass-deleted-a-production-config-and-nano-couldnt-save-me-4357f13badfb"><strong>Post 0 — I Mass-Deleted a Production Config and nano Couldn’t Save Me</strong></a></li><li><a href="https://adityakrsingh26.medium.com/taking-over-the-terminal-raw-mode-and-escape-codes-4ad4aac06943"><strong>Post 1 — Taking Over the Terminal: Raw Mode and Escape Codes</strong></a></li><li><a href="https://adityakrsingh26.medium.com/decoding-the-keyboard-why-your-arrow-keys-send-three-bytes-e9eb95a0ec6e"><strong>Post 2 — Decoding the Keyboard: Why Your Arrow Keys Send Three Bytes</strong></a></li><li><a href="https://adityakrsingh26.medium.com/storing-text-without-losing-your-mind-or-your-unicode-21dc6deb9565"><strong>Post 3 — Storing Text Without Losing Your Mind (or Your Unicode)</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/painting-pixels-in-a-world-made-of-characters-e18e21ba357d"><strong>Post 4 — Painting Pixels in a World Made of Characters</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/the-state-machine-that-makes-modal-editing-click-57c817199da4"><strong>Post 5 — The State Machine That Makes Modal Editing Click</strong></a></li><li><a href="https://adityakrsingh26.medium.com/3dd-and-the-algebra-of-vim-commands-f0964b80bdfe?postPublishedType=repub"><strong>Post 6–3dd and the Algebra of Vim Commands</strong></a></li></ul><p>GitHub : <a href="https://github.com/AdityaKrSingh26/Glime"><strong>github.com/AdityaKrSingh26/Glime</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4197a6a577d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3dd and the Algebra of Vim Commands]]></title>
            <link>https://adityakrsingh26.medium.com/3dd-and-the-algebra-of-vim-commands-f0964b80bdfe?source=rss-5e24f1119e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0964b80bdfe</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Aditya Kumar Singh]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 07:30:23 GMT</pubDate>
            <atom:updated>2026-03-31T18:55:22.780Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time you see someone type 3dd in Vim, it feels like magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Y_0UMoPFU7kcr6XDmQ35w.png" /></figure><p>Three lines disappear instantly. It looks like a shortcut. Something memorized. Something hidden in a cheat sheet.</p><p>It’s not.</p><p>It’s a sentence.</p><ul><li>3 → the count</li><li>d → the operator (delete)</li><li>d → the motion (current line)</li></ul><p>Put together, it reads naturally:</p><p><strong><em>“Delete 3 lines.”</em></strong></p><p>That’s the core idea behind Vim. You’re not memorizing commands. You’re composing them.</p><p>Once you understand the grammar, you stop learning commands one by one. Instead, you generate them.</p><ul><li>5j → move down 5 lines</li><li>dw → delete a word</li><li>y$ → copy to end of line</li></ul><p>Never seen y$ before? Doesn’t matter. The grammar gives it to you.</p><p>This post walks through how to build that grammar into an editor.</p><h3>The Grammar</h3><p>Every Vim command in normal mode follows the same pattern:</p><pre>[count] [operator] [motion]</pre><p><strong>Count</strong> is an optional number prefix. If you don’t provide one, it defaults to 1. If you type 5, it means &quot;do this 5 times.&quot;</p><p><strong>Operator</strong> is what to do. d means delete. y means yank (copy). Not every command has an operator sometimes you just have a motion by itself.</p><p><strong>Motion</strong> is what to do it on. d means &quot;current line&quot; (only when paired with the d operator dd). w means &quot;to the next word.&quot; $ means &quot;to the end of the line.&quot; j means &quot;down one line.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWqNTbgnYoAE_9RxeDuzpg.png" /></figure><h3>Motions Without Operators</h3><p>Some commands are just movements:</p><ul><li>h j k l → left, down, up, right</li><li>w b → next word, previous word</li><li>gg → first line</li><li>G → last line</li><li>0 → start of line</li><li>$ → end of line</li></ul><p>These also accept counts: 5j → move down 5 lines</p><h3>Combining Operator + Motion</h3><p>This is where things become powerful.</p><ul><li>dw → delete word</li><li>d$ → delete to end of line</li><li>3dd → delete 3 lines</li></ul><p>The operator acts on whatever range the motion defines.</p><p>That’s the entire language.</p><h3>The Real Problem: Multi-Key Commands</h3><p>When a user presses d, you don’t know what to do yet.</p><ul><li>dd?</li><li>dw?</li><li>d$?</li></ul><p>You need to <strong>wait for the next key</strong>.</p><p>This means your editor needs <strong>state between keystrokes</strong>.</p><h3>PendingCommand: Tracking Multi-Key State</h3><p>Here’s the problem. When the user presses d, the editor doesn&#39;t know what to do yet. Is it dd? dw? d$? The editor has to wait for the next key.</p><p>This means we need state between keystrokes. We need to remember: “<em>the user pressed </em><em>d, and I&#39;m waiting for the motion.</em>&quot; We also need to remember any count prefix that came before the operator.</p><p>The struct that tracks all of this:</p><pre>struct PendingCommand:<br>    count: integer<br>    operator: character (or null)<br>    has_count: boolean<br><br>function accumulate_digit(pending, digit):<br>    pending.count = pending.count * 10 + digit<br>    pending.has_count = true<br><br>function effective_count(pending):<br>    if pending.count == 0: return 1<br>    return pending.count<br><br>function reset(pending):<br>    pending.count = 0<br>    pending.operator = null<br>    pending.has_count = false</pre><p>The count field accumulates digits as the user types them. If the user types 1 then 2, the count becomes 12. The has_countflag tells us whether the user has started typing a number this matters because 0 by itself means &quot;go to start of line,&quot; but 10 means &quot;count is ten.&quot; We need to distinguish &quot;no count yet&quot; from &quot;count is zero.&quot;</p><p>The operator field stores the pending operator. When it&#39;s null (or zero), there&#39;s no operator waiting. When it&#39;s d, we&#39;re waiting for a motion to tell us what to delete.</p><p>reset() clears everything. We call it after executing a command, after pressing Escape, and after any non-rune key (arrows, Page Up, etc.).</p><h3>Normal Mode Dispatch</h3><p>Now we need the logic that reads keys and decides what to do. The dispatch happens in stages:</p><ol><li><strong>Non-rune keys come first.</strong> Arrow keys, Page Up/Down, Escape, Ctrl combos these are handled immediately and reset any pending state. You don’t want d followed by an arrow key to delete something. It should just move.</li><li><strong>Digits accumulate the count.</strong> If the key is 1 through 9, it&#39;s part of the count prefix. If it&#39;s 0 and a count has already started, it&#39;s also part of the count (making 10, 20, 100, etc.). If it&#39;s 0 and no count has started, it means &quot;go to start of line.&quot;</li><li><strong>Operators wait.</strong> If there’s no operator pending yet and the key is d, y, or g, store it as the pending operator and return. Don&#39;t do anything else. Wait for the motion.</li><li><strong>Execute.</strong> If we get here, we have a key that’s not a digit, not an operator-start, and not a non-rune key. It’s either a motion (with or without a pending operator) or a standalone command. Execute it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFeHG1LsgVkPEl5eJuzG6A.png" /></figure><p>Here’s the pseudocode:</p><pre>function process_normal_mode(key):<br>    // Step 1: Non-rune keys<br>    if key is arrow/page/escape/ctrl:<br>        reset(pending)<br>        handle the key directly<br>        return<br><br>    if key is not a printable character:<br>        return<br><br>    ch = key.character<br>    <br>    // Step 2: Count prefix<br>    if ch is &#39;1&#39; through &#39;9&#39;:<br>        accumulate_digit(pending, ch - &#39;0&#39;)<br>        return<br>    if ch is &#39;0&#39; and pending.has_count:<br>        accumulate_digit(pending, 0)<br>        return<br><br>    // Step 3: Operator pending<br>    if pending.operator is null:<br>        if ch is &#39;d&#39; or &#39;y&#39; or &#39;g&#39;:<br>            pending.operator = ch<br>            return<br><br>    // Step 4: Execute<br>    execute_command(ch, pending)</pre><p>The execute_command function is where the operator + motion combinations get resolved:</p><pre>function execute_command(ch, pending):<br>    count = effective_count(pending)<br>    op = pending.operator<br>    reset(pending)<br><br>    if op is not null:<br>        // Operator + motion<br>        if op == &#39;d&#39;:<br>            if ch == &#39;d&#39;: delete_lines(count)<br>            if ch == &#39;w&#39;: delete_word(count)<br>            if ch == &#39;$&#39;: delete_to_end()<br>        if op == &#39;y&#39;:<br>            if ch == &#39;y&#39;: yank_lines(count)<br>            if ch == &#39;w&#39;: yank_word(count)<br>            if ch == &#39;$&#39;: yank_to_end()<br>        if op == &#39;g&#39;:<br>            if ch == &#39;g&#39;: go_to_first_line()<br>        return<br><br>    // No operator — standalone commands<br>    if ch == &#39;h&#39;: move_left(count)<br>    if ch == &#39;j&#39;: move_down(count)<br>    if ch == &#39;k&#39;: move_up(count)<br>    if ch == &#39;l&#39;: move_right(count)<br>    if ch == &#39;w&#39;: move_to_next_word(count)<br>    if ch == &#39;b&#39;: move_to_prev_word(count)<br>    if ch == &#39;0&#39;: move_to_line_start()<br>    if ch == &#39;$&#39;: move_to_line_end()<br>    if ch == &#39;G&#39;: go_to_last_line()<br>    if ch == &#39;x&#39;: delete_char_under_cursor()<br>    if ch == &#39;u&#39;: undo()<br>    if ch == &#39;p&#39;: paste_after()<br>    if ch == &#39;P&#39;: paste_before()<br>    // ... and so on</pre><p>Notice how $ appears in two places. As a standalone motion, it moves the cursor to the end of the line. As a motion after the d operator, it deletes to the end of the line. Same key, different context. That&#39;s the grammar at work.</p><p>Also notice gg. The user presses g, which stores g as the pending operator. Then they press g again. Now execute_commandsees operator g and motion g that&#39;s &quot;go to first line.&quot; If they had pressed g followed by some other key, we&#39;d just ignore it. The g prefix is our extension point for two-character commands.</p><h3>Word Boundaries</h3><p>To make w, b, dw, and yw work, we need to know where words start and end. This sounds simple until you think about what a &quot;word&quot; is.</p><p>In Vim, a word is a sequence of word characters (letters, digits, underscore) or a sequence of non-whitespace, non-word characters (punctuation). Whitespace separates words. So in the line foo_bar + baz, there are three words: foo_bar, +, and baz.</p><p>The w motion moves forward to the start of the next word. The algorithm:</p><ol><li>Look at the character under the cursor. Classify it: word character, punctuation, or whitespace.</li><li>Skip forward through characters of the same class. If you’re on a word character, skip word characters. If you’re on punctuation, skip punctuation. If you’re on whitespace, skip whitespace</li><li>Skip any trailing whitespace.</li><li>You’re now at the start of the next word. If you went past the end of the line, go to the start of the next line.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qRmgSDgpbzClPBd3ERKhA.png" /></figure><p>Here’s the pseudocode:</p><pre>function find_word_end(row, col):<br>    chars = get_characters(lines[row])<br><br>    // handle empty lines<br>    while col &gt;= length(chars):<br>        if row &lt; last_line:<br>            row++; col = 0; chars = get_characters(lines[row])<br>        else: return row, col<br><br>    // determine character class at current position<br>    ch = chars[col]<br>    is_word = is_word_char(ch)<br>    is_punct = not is_word and not is_space(ch)<br><br>    // skip same class<br>    while col &lt; length(chars):<br>        c = chars[col]<br>        if is_word and not is_word_char(c): break<br>        if is_punct and (is_word_char(c) or is_space(c)): break<br>        if is_space(ch) and not is_space(c): break<br>        col++<br><br>    // skip trailing whitespace<br>    while col &lt; length(chars) and is_space(chars[col]):<br>        col++<br><br>    // if we went past the line, go to start of next<br>    if col &gt;= length(chars) and row &lt; last_line:<br>        return row + 1, 0<br><br>    return row, col</pre><p>For the backward motion b, the algorithm is similar but in reverse:</p><ol><li>Move back one position.</li><li>Skip whitespace backward.</li><li>Look at the character you’ve landed on. Skip backward through characters of the same class (word chars or punctuation).</li><li>You’re at the start of the word.</li></ol><pre>function find_word_start(row, col):<br>    // if at start of line, jump to end of previous line<br>    if col == 0:<br>        if row &gt; 0:<br>            prev_chars = get_characters(lines[row - 1])<br>            if length(prev_chars) == 0: return row - 1, 0<br>            return row - 1, length(prev_chars) - 1<br>        return 0, 0<br><br>    chars = get_characters(lines[row])<br>    col--  // move back one<br><br>    // skip whitespace backward<br>    while col &gt; 0 and is_space(chars[col]):<br>        col--<br><br>    if col == 0: return row, 0<br><br>    // determine class at current position<br>    ch = chars[col]<br>    is_word = is_word_char(ch)<br><br>    // skip same class backward<br>    while col &gt; 0:<br>        prev = chars[col - 1]<br>        if is_word and not is_word_char(prev): break<br>        if not is_word and (is_word_char(prev) or is_space(prev)): break<br>        col--<br><br>    return row, col</pre><p>The helper is_word_char is just:</p><pre>function is_word_char(ch):<br>    return is_letter(ch) or is_digit(ch) or ch == &#39;_&#39;</pre><h3>Delete Operations</h3><p>Now that we have the dispatch system and word boundaries, let’s wire up the operations that actually change text. Deleting is more than removing characters. Every delete needs to:</p><ol><li>Save the deleted text to the register (so you can paste it later).</li><li>Record undo actions (so you can undo the delete).</li><li>Perform the deletion on the buffer.</li><li>Adjust the cursor.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhddTvC-i5XZQnlrt0Hlqg.png" /></figure><h4>dd: Delete Lines</h4><p>The simplest operator-motion pair. dd deletes the current line. 3dd deletes 3 lines starting from the cursor.</p><pre>function delete_lines(count):<br>    row = cursor.row<br>    lines = get_all_lines()<br><br>    // clamp count to remaining lines<br>    if count &gt; length(lines) - row:<br>        count = length(lines) - row<br><br>    // yank before deleting<br>    yanked = join(lines[row .. row + count], &quot;\n&quot;)<br>    register = { content: yanked, type: LINE }<br><br>    // record undo (reverse order so undo re-inserts bottom-up)<br>    begin_undo_group()<br>    for i = count - 1 down to 0:<br>        record_undo(DELETE_LINE, row + i, lines[row + i])<br><br>    // delete the lines<br>    for i = 0 to count - 1:<br>        delete_line(row)  // always delete at &#39;row&#39; because lines shift up<br>    end_undo_group()<br><br>    // adjust cursor<br>    if row &gt;= total_lines(): row = total_lines() - 1<br>    if row &lt; 0: row = 0<br>    move_cursor(row, 0)</pre><p>A few things to notice. When recording undo actions, we go in reverse order (from the last line to the first). This is because when we undo, the actions replay in reverse. If we recorded them top-to-bottom and then replayed bottom-to-top, the row indices would be wrong reinserting line 5 before line 3 has been reinserted would put things in the wrong place.</p><p>When performing the actual deletions, we always delete at the same row index. After deleting row 5, what was row 6 is now row 5. So we delete at row each time, not at row + i.</p><h4>dw: Delete Word</h4><p>dw deletes from the cursor to the start of the next word. The approach: find where the word motion would take us, then delete everything between the cursor and that position.</p><p>For a same-line deletion, we replace the line content. For a multi-line deletion (rare, but possible if the word spans a line boundary), we merge the remaining parts and delete the intermediate lines.</p><h4>d$: Delete to End of Line</h4><p>The simplest of the three. Take everything from the cursor column to the end of the line, save it to the register, and replace the line with just the part before the cursor.</p><h3>The Register System</h3><p>Every time you delete or yank text, it goes into a register. The register is just a clipboard. It holds one piece of text at a time.</p><p>But it needs to remember <em>how</em> the text was copied, because that changes how paste works. If you deleted a line with dd, pasting should insert a new line. If you deleted a word with dw, pasting should insert characters at the cursor position.</p><pre>enum RegisterType: CHAR, LINE<br><br>struct Register:<br>    content: string<br>    type: RegisterType</pre><p>That’s it. Two fields. The type tells the paste function whether to insert lines or characters.</p><p>In a full Vim implementation, there are 26 named registers (&quot;a through &quot;z), a clipboard register, a numbered register for each recent delete, and more. We&#39;re building one unnamed register. It covers 90% of real usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsHPANQADZlwBeKRthxxGw.png" /></figure><h3>Yank</h3><p>Yanking is copying without deleting. yy copies the current line. 2yy copies 2 lines. yw copies from the cursor to the next word boundary. y$ copies from the cursor to the end of the line.</p><p>The implementation is the same as the delete operations, minus the deletion. Find the text range, store it in the register, don’t touch the buffer.</p><pre>function yank_lines(count):<br>    row = cursor.row<br>    lines = get_all_lines()<br><br>    if count &gt; length(lines) - row:<br>        count = length(lines) - row<br><br>    yanked = join(lines[row .. row + count], &quot;\n&quot;)<br>    register = { content: yanked, type: LINE }<br>    show_message(count + &quot; lines yanked&quot;)</pre><p>No undo recording. No buffer changes. Just fill the register and tell the user what happened.</p><h3>Paste</h3><p>Paste is where the register type matters. p pastes after the cursor. P pastes before the cursor. But &quot;after&quot; and &quot;before&quot; mean different things depending on whether the register holds lines or characters.</p><p><strong>Line paste</strong> (RegisterLine): p inserts the lines below the current line. P inserts them above. The cursor moves to the first inserted line.</p><p><strong>Character paste</strong> (RegisterChar): p inserts the text after the cursor column. P inserts it at the cursor column. The cursor moves to the end of the pasted text.</p><pre>function paste(after_cursor):<br>    if register is empty: return<br><br>    if register.type == LINE:<br>        insert_row = cursor.row + (1 if after_cursor else 0)<br>        lines_to_paste = split(register.content, &quot;\n&quot;)<br>        for i, line in lines_to_paste:<br>            insert_line_with_content(insert_row + i, line)<br>        move_cursor(insert_row, 0)<br>    else:<br>        // character paste<br>        insert_col = cursor.col + (1 if after_cursor else 0)<br>        line = get_line(cursor.row)<br>        runes = get_characters(line)<br>        if insert_col &gt; length(runes):<br>            insert_col = length(runes)<br>        new_line = runes[0..insert_col] + register.content + runes[insert_col..]<br>        set_line(cursor.row, new_line)<br>        move_cursor(cursor.row, insert_col + length(register.content) - 1)</pre><p>The character paste clamps insert_col to the line length. If you&#39;re at the end of the line and press p, it appends the text rather than going past the end.</p><p>Both paths wrap their changes in an undo group, so a single u will undo the entire paste.</p><h3>Putting It All Together</h3><p>Let’s trace through 3dd to see the whole system in action.</p><ol><li>User presses 3. The dispatch sees a digit, calls AccumulateDigit(3). Pending state: {Count: 3, Operator: 0, HasCount: true}.</li><li>User presses d. No operator pending yet, and d is an operator. Store it. Pending state: {Count: 3, Operator: &#39;d&#39;, HasCount: true}.</li><li>User presses d. There&#39;s already an operator pending, so this isn&#39;t treated as a new operator. We fall through to executeNormalCommand(&#39;d&#39;). The function sees op == &#39;d&#39; and ch == &#39;d&#39;, so it calls deleteLines(3).</li><li>deleteLines(3) yanks 3 lines into the register as RegisterLine, records 3 DeleteLine undo actions in reverse order, deletes the 3 lines from the buffer, and adjusts the cursor.</li></ol><p>Now the user can press p to paste those 3 lines below the cursor. Or u to undo the deletion. The grammar flows through every piece: dispatch to operation to register to undo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Kw7u9yKcrkAc0WwWxO7Ig.png" /></figure><h3>What You Built</h3><p>This post added the composable command system that makes Vim feel like Vim:</p><ul><li><strong>Count + operator + motion grammar.</strong> A PendingCommand struct accumulates the count and stores the operator while waiting for the motion. The dispatch function routes through four stages: non-rune keys, digit accumulation, operator storage, and command execution.</li><li><strong>Word navigation.</strong> findWordEnd and findWordStart classify characters into word chars, punctuation, and whitespace, then skip through same-class runs to find boundaries. These power the w and b motions.</li><li><strong>Delete operations.</strong> dd deletes lines, dw deletes to the next word, d$ deletes to end of line. Every deletion saves to the register and records undo actions.</li><li><strong>Register system.</strong> A single register with a type (RegisterChar or RegisterLine) that determines how paste behaves. Deletes and yanks fill it. Paste reads from it.</li><li><strong>Yank and paste.</strong> yy and yw copy without deleting. p and P paste after or before the cursor, inserting lines or characters depending on the register type.</li></ul><p>The commands are composable because the same machinery handles all of them. Adding a new motion (like e for end-of-word or } for next paragraph) means adding one case to the operator switch and one case to the standalone switch. The count, undo, and register logic come for free.</p><h3>What’s Next ?</h3><p><strong>Next</strong> <a href="https://medium.com/@adityakrsingh26/time-travel-building-undo-that-actually-works-4197a6a577d2"><strong>Post 7–Time Travel: Building Undo That Actually Works</strong></a></p><p><strong>Previous:</strong></p><ul><li><a href="https://adityakrsingh26.medium.com/i-mass-deleted-a-production-config-and-nano-couldnt-save-me-4357f13badfb"><strong>Post 0 — I Mass-Deleted a Production Config and nano Couldn’t Save Me</strong></a></li><li><a href="https://adityakrsingh26.medium.com/taking-over-the-terminal-raw-mode-and-escape-codes-4ad4aac06943"><strong>Post 1 — Taking Over the Terminal: Raw Mode and Escape Codes</strong></a></li><li><a href="https://adityakrsingh26.medium.com/decoding-the-keyboard-why-your-arrow-keys-send-three-bytes-e9eb95a0ec6e"><strong>Post 2 — Decoding the Keyboard: Why Your Arrow Keys Send Three Bytes</strong></a></li><li><a href="https://adityakrsingh26.medium.com/storing-text-without-losing-your-mind-or-your-unicode-21dc6deb9565"><strong>Post 3 — Storing Text Without Losing Your Mind (or Your Unicode)</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/painting-pixels-in-a-world-made-of-characters-e18e21ba357d"><strong>Post 4 — Painting Pixels in a World Made of Characters</strong></a></li><li><a href="https://medium.com/@adityakrsingh26/the-state-machine-that-makes-modal-editing-click-57c817199da4"><strong>Post 5 — The State Machine That Makes Modal Editing Click</strong></a></li></ul><p>GitHub : <a href="https://github.com/AdityaKrSingh26/Glime"><strong>github.com/AdityaKrSingh26/Glime</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0964b80bdfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>