AI 资讯
The Principle of Least Privilege: Why File Permissions Like 600/644/755 Exist
Anyone who has worked with SSH private keys has run into an instruction to "set it to 600." Config files, by contrast, often get 644, and executable scripts get 755. What do these three-digit numbers actually mean, and why does the right number depend on what kind of file you're dealing with? This post starts from the mechanics of Unix-style (Mac/Linux) file permissions and works up to the design principle behind them: least privilege. Permissions as a 2D grid of who and what Unix-family operating systems express file access as a grid: three kinds of "who" crossed with three kinds of "what." "Who" breaks down into the file's owner, the group the owner belongs to, and everyone else ("other"). "What" breaks down into read, write, and execute. Each cell in that 3×3 grid is either granted or not, and that's exactly what a listing like -rw-r--r-- from ls -l is showing you. Strip the leading character and the remaining nine characters are three groups of three — owner, group, other — each rendered as r/w/x when granted or - when not. Why a single digit can represent read/write/execute Numeric notation like chmod 600 compresses that rwx combination into a single octal digit. Read is worth 4, write is worth 2, execute is worth 1 — powers of two — and you sum whichever bits are set. Note: powers of two are used here because each of read/write/execute is tracked as an independent bit (on or off), and any sum of a subset of {4, 2, 1} maps back to exactly one combination of bits. There's no ambiguity — for example, 6 can only mean read+write (4+2), never any other combination. Read and write, no execute ( rw- ): 4 + 2 = 6 Read only ( r-- ): 4 Read, write, and execute ( rwx ): 4 + 2 + 1 = 7 No access at all ( --- ): 0 A three-digit number like 600 lines up these single digits for owner, group, and other, left to right. 600 means "owner gets read+write, group and other get nothing." What the common numbers actually mean Reading the numbers mentioned at the top through this lens:
AI 资讯
The Active Flag Trap: unvalidated-but-logged-in in CakeDC/Users
If you ship email validation with CakeDC/Users , you eventually hit a question the plugin quietly hands back to you: what should happen when someone registers, never clicks the validation link, and then tries to log in? The honest answer is that CakeDC/Users doesn't decide for you. Out of the box you get a database column, a couple of behaviors, and a set of events — but the experience is yours to assemble. Get it wrong and you land in one of two bad places: a user silently logged in without ever validating, or a user who typed the right password and is told "username or password is incorrect." Neither is what you want. This post walks through why that happens in v16, and a clean way to wire the flow using the events the plugin already dispatches — no core hacks, no schema surgery. One flag, two meanings Everything starts with a single boolean column on the users table: active . When email validation is on, registration creates the account with active = 0 and only flips it to 1 when the user clicks the link in the validation email. You can trace it in BaseTokenBehavior::_updateActive() : // $user['validated'] is a transient flag set to false during register() $emailValidated = $user [ 'validated' ]; if ( ! $emailValidated && $validateEmail ) { $user [ 'active' ] = false ; // registered → inactive + token emailed $user -> updateToken ( $tokenExpiration ); } else { $user [ 'active' ] = true ; // clicked the link → active $user [ 'activation_date' ] = new DateTime (); } Notice there is no separate validated column in the database — $user['validated'] is a transient property used only during registration. The persisted truth is active , and it is doing two jobs at once: "Has this person confirmed their email?" — set by the validation flow. "Is this account enabled?" — the thing an admin toggles to ban or suspend someone. That conflation is the root of everything below. Hold onto it; we'll come back to it. How the finder decides who exists Login in CakeDC/Users runs thro
AI 资讯
Why I Built a Zero-Knowledge, Client-Side Encrypted Burning Note App Over the Weekend
Hey everyone! 👋 Like many developers and sysadmins, I constantly find myself needing to share temporary credentials, API keys, or sensitive text with clients and coworkers. Dropping these straight into Slack, Discord, or standard email always feels like a massive security headache because those chat platforms store everything in plain text in their databases. I looked into popular "one-time secret" web utilities, but I noticed a major flaw: almost all of them handle the encryption and decryption on their servers. That means you have to blindly trust their backend configurations, logging policies, and database security. I wanted something truly zero-knowledge where the server owner physically couldn't read the notes even if they wanted to. So, I built ScorchNote : https://scorchnote.com 🛠️ How it Works (Under the Hood) To achieve absolute zero-knowledge, ScorchNote relies on strict client-side mechanics: Browser-Side Encryption: When you type a secret, the data is encrypted directly in your browser before it ever leaves your network interface. The URL Hash Advantage: The decryption key is generated and stored inside the URL's hash fragment (everything after the # ). Zero Server Footprint: Web browsers never send the hash fragment to the host server during HTTP requests. This means my database only receives a completely scrambled, encrypted payload. The server has no concept of what the key is. Millisecond Burn-on-Read: The moment the recipient visits the link, the encrypted payload is fetched and instantly purged from the server database. 🚀 Try It Out I kept the page entirely lightweight, minimalist, and completely free of bloated tracking scripts. It’s built to do exactly one job, safely and instantly. I would love to hear your thoughts on the architecture, the user experience, or what features you think I should cook up next! Check it out here: ScorchNote
AI 资讯
Buying a phone number is a distributed transaction
The API makes it look trivial. const number = await carrier . numbers . buy ({ phone_number : " +1... " }); await db . insert ( " rented_numbers " , { user_id , e164 : number . phone_number }); await stripe . subscriptions . create ({ customer , price }); Three lines, one number, done. Ship it. What you actually wrote is a distributed transaction across three systems. They share no transaction log, they have no two-phase commit, and none of them can roll back the others. The carrier will keep charging you for a number your database has never heard of. Stripe will stop charging for a number your database still thinks is paid up. Neither one is going to mention it. I run a virtual phone number product. Below are the failure modes that actually cost us money, roughly in order of how much. The orphan taxonomy Write down the states first, because the interesting ones are the states nobody designs for. Three systems, each holding an opinion about a single number: Your DB Carrier Stripe What is actually happening active owns it active The happy path. Rare in the tail. no row owns it nothing You pay monthly rent on a number nobody can see or use. active released active You bill a customer for a number you no longer own. pending_cancellation owns it canceled Customer stopped paying. You are still paying the carrier. active owns it canceled You provide service for free, indefinitely. cancelled owns it canceled Release failed at teardown. Silent monthly bleed. Every row under the first one is reachable from a plain network timeout at a bad moment. The first orphan class is the worst, because you cannot see it from inside your own product. No row, no user, no support ticket. The number sits in the carrier's inventory producing an invoice line every month until somebody actually reads the invoice. The second class is the one that generates a complaint. The rest leak money in one direction or the other, quietly. Reconcile, don't prevent The instinct is to armour the write path. S
AI 资讯
Clean code isn't what I thought it was
What working on real systems taught me about maintainable code. My second job was the first time I worked with an international team where everyone had ten or more years of experience. I had maybe two. It was also the first time I was part of proper code reviews, branching strategies, and pull request workflows. Everything felt new and slightly intimidating. One of my first tasks was adding spacing between two elements. It should have been a simple margin or padding change, but I added a <br> tag instead. The feedback on that PR was polite but clear, and it made me a little embarrassed. That moment, along with dozens of similar ones, made me want to get better. I started reading about clean code and caring deeply about how my code looked. Small functions, no repetition, everything abstracted and organized. For a while, that served me well. It helped me grow from a junior developer into someone who could write code that passed review without a wall of comments. But over time, as I worked on larger systems with real users and real constraints, I started noticing that the rules I had learned didn't always hold up. Sometimes the "clean" approach made things worse, and sometimes messy-looking code worked better than the elegant version I would have written. This post is about how my definition of clean code expanded. I still believe in the principles I learned early on. I'd just add a few things to them now. What I thought clean code meant When I first started paying attention to code quality, my idea of clean code was mostly about appearances. If the code looked organized and followed certain patterns, it was clean. If it didn't, it wasn't. I believed in small functions for everything. If a function was longer than fifteen or twenty lines, something was wrong. I would extract pieces into helpers even when they were only used once, just because the parent function felt "too long." I was strict about DRY. Any time I saw similar logic in two places, I would immediately pul
AI 资讯
Building File Utilities That Run 100% in the Browser
I recently built filetools, a suite of file utilities that run entirely in the browser. No server backend, no file uploads, no data collection. The Problem Existing tools for CSV extraction, PDF manipulation, and table conversion often require uploading files or creating accounts. That creates friction and privacy concerns. But these tasks are fundamentally simple: extracting text from a PDF or parsing a CSV can happen entirely in JavaScript. The Solution filetools is a collection of single-purpose utilities: PDF Tools: Merge, split, rotate PDFs Extract tables from PDFs to CSV Convert bank statements to CSV Data Tools: Extract tables from HTML to CSV or JSON Convert between XLSX, JSON, YAML, and CSV Remove duplicate lines, sort CSV files, merge/compare data files Each tool is its own page, targeting one specific task without bloat. Architecture Why static hosting? Keeps infrastructure simple and costs near zero. Files are built once, served from GitHub Pages. Why client-side only? User files never leave their machine. Processing is fast (no network round-trip). Privacy is the default. Tech stack: vanilla JavaScript using npm libraries (pdfjs-dist, exceljs, js-yaml, pdf-lib) - no framework, no server. Each page is roughly 5-15KB gzipped. Design: Started with demand mining, looking at actual Google search queries and autocomplete suggestions to pick which tools to build first. What's Next Live site: https://usefiletools.com/?utm_source=dev.to&utm_medium=article&utm_campaign=filetools-launch I'm building more tools based on real search demand. If there's a file utility you've always wished existed, especially for data professionals, I'd love to hear about it.
AI 资讯
Enterprise MCP Gateway Solutions: Providers, Alternatives, and Cost 💎
Your company uses six different AI providers. OpenAI for ChatGPT, Anthropic for Claude and Groq for speed critical inference. Each one has different API formats. Different authentication models. Different rate limits and costs. Different failure modes. Your application code has to know about all of them. Your security team has to audit requests across all of them. Your finance team has to track costs across all of them. Your compliance team has to ensure governance across all of them. Bifrost Gateway solves this by doing what HTTP gateways have done for decades: centralizing control . But for AI. 👀 What is an MCP gateway? Model Context Protocol (MCP) is an open standard that lets AI models discover and execute external tools at runtime filesystems, web search, databases, ticketing systems, and custom business logic instead of being limited to text generation. An MCP gateway sits between your applications (or external MCP clients like Claude Desktop and Cursor) and the upstream MCP servers. Instead of each client maintaining its own connections, credentials, and tool lists, the gateway: Aggregates tools from multiple MCP servers into one registry Applies governance : authentication, tool filtering, budgets, and rate limits Exposes a single endpoint that external MCP clients can connect to In Bifrost, this pattern is implemented in two complementary roles: Role What it does MCP Client Connects to external MCP servers via STDIO, HTTP, or SSE MCP Server (Gateway) Exposes aggregated tools at /mcp for Claude Desktop, Cursor, and other MCP-compatible clients Bifrost is both an AI gateway (routing LLM traffic to 20+ providers) and an MCP gateway (connecting to and exposing tool servers). The open-source gateway covers virtual keys, budgets, rate limits, routing, and MCP tool filtering. Bifrost Enterprise adds RBAC, SSO, audit logs, MCP Tool Groups, guardrails, clustering, and in-VPC deployment options. ⚙️ How does an MCP gateway work? Connection layer Each upstream MCP serv
AI 资讯
How to pull every open job from Greenhouse, Lever, Ashby and SmartRecruiters with public APIs (and monitor changes)
Job postings are one of the most underrated public data sources on the internet. Recruiters use them to spot placement opportunities, B2B teams read them as buying signals (a new Head of Data means data-tooling budget), and job seekers want to apply on day one — not when a posting finally reaches the aggregators. The usual instinct is to scrape career pages. Don't. Most tech companies host their careers page on one of a handful of Applicant Tracking Systems (ATS), and the four biggest ones — Greenhouse, Lever, Ashby and SmartRecruiters — all expose public, documented JSON APIs . No auth. No proxies. No brittle HTML selectors. The career page itself loads the same JSON you're about to fetch. In this tutorial we'll build a single-file Python tool that: fetches every open job for a company from any of the four ATS, auto-detects which ATS a company uses, normalizes everything into one clean schema, monitors changes — run it on a schedule and get only new / removed / changed postings. The four endpoints ATS Endpoint Greenhouse GET https://boards-api.greenhouse.io/v1/boards/{slug}/jobs?content=true Lever GET https://api.lever.co/v0/postings/{slug}?mode=json Ashby GET https://api.ashbyhq.com/posting-api/job-board/{slug} SmartRecruiters GET https://api.smartrecruiters.com/v1/companies/{slug}/postings (paginated) The {slug} is the company identifier you see in career-page URLs: boards.greenhouse.io/stripe → stripe , jobs.lever.co/spotify → spotify , jobs.ashbyhq.com/linear → linear , careers.smartrecruiters.com/Visa → Visa . Try one right now — no API key needed: curl -s "https://api.ashbyhq.com/posting-api/job-board/linear" | head -c 400 Step 1 — fetchers, one per ATS Each API returns a different shape, so we normalize as we fetch. Here are all four (Python 3, only requests ): import requests UA = { " User-Agent " : " ats-jobs-tutorial/1.0 " } def get_json ( url , params = None ): r = requests . get ( url , params = params , headers = UA , timeout = 30 ) r . raise_for_statu
AI 资讯
🎬 Reel Quick now has a live animated demo in the GitHub README
The demo gives a quick look at the workflow for creating short-form videos with trimming, stitching, text overlays, voice tools, themes, and transitions. Built with FastAPI, Next.js, Redis/ARQ, and FFmpeg. Repo: https://github.com/ronin1770/reel-quick OpenSource #Python #FastAPI #NextJS #FFmpeg #VideoAutomation #DeveloperTools #AI
AI 资讯
The Midnight wallet SDK changed its npm scope. Here is what to update.
If you installed the Midnight wallet SDK a while back and pinned the package names, your imports are now pointing at a deprecated scope. Nothing is broken yet. But the packages you depend on moved, and the old names are living on borrowed time. Here is what changed, why it matters, and the one gotcha that trips people up. The short version The wallet SDK packages moved from the @midnight-ntwrk scope (with a dash) to @midnightntwrk (no dash). @midnight-ntwrk/wallet-sdk-facade -> @midnightntwrk/wallet-sdk-facade The old dashed packages still install, so your build keeps working for now. They are published as a transitional alias. But the dashed scope is deprecated, and the newest releases only show up on the new no-dash scope. So you want to move over. There is one exception. @midnight-ntwrk/ledger-v8 stays on the dashed scope. Do not rename that one. More on that below. What actually changed Straight from the wallet SDK v1.2.0 release notes: the npm scope has changed from @midnight-ntwrk to @midnightntwrk (no dash). New installs should depend on @midnightntwrk/* . The old @midnight-ntwrk/* packages continue to be published as a transitional alias during the migration window, so existing consumers keep working, but the dashed scope is deprecated. So both scopes exist on npm right now. That is why nothing breaks. But they are not equal. The no-dash scope is where the active releases land, and the dashed scope lags behind. You can see it yourself. Here are the current latest versions, dashed vs no-dash: Package Dashed (old) No-dash (new) wallet-sdk-facade 4.0.1 4.1.0 wallet-sdk-hd 3.0.2 3.0.3 wallet-sdk-shielded 3.0.1 3.0.2 wallet-sdk-dust-wallet 4.1.0 4.2.0 If you stay on the dashed names, you quietly get the older packages. The version fixes and new features go to the no-dash scope first. The gotcha: ledger-v8 does not move This is the part that catches people. When you do a find and replace across your project, it is tempting to swap every @midnight-ntwrk for @midnig
AI 资讯
How to Create Your Own Claude Code Skill With SKILL.md
If you use Claude Code for frontend development, you may have noticed something. Claude can write code very fast. But sometimes the UI it creates looks too similar to other AI-generated websites. You get the same rounded cards, large headings, soft shadows, gradients, and simple layouts. The code works. But the design does not always feel like your own. Hi everyone, I am Henry. In this article, I want to show you a simple way to fix that. We are going to create our own Claude Code Skill using a SKILL.md file. You do not need to build a complicated tool. You just need a clear set of instructions that Claude can follow when working on your frontend. What Is a Claude Code Skill? A Claude Code Skill is a reusable set of instructions for a specific type of work. For example, you can create a skill for: Frontend design Testing Documentation Code review Database work DevOps UI accessibility For this tutorial, we will create a frontend design skill . Our goal is simple: Help Claude create clean frontend UI without falling back to the same generic design patterns. Instead of writing the same design rules in every prompt, we can keep them inside a skill. Step 1: Create the Skill Folder Open your project in the terminal. Create a .claude folder if you do not already have one. Then create a skills folder: mkdir -p .claude/skills/frontend-design Now create the skill file: touch .claude/skills/frontend-design/SKILL.md Your project should now look something like this: your-project/ ├── .claude/ │ └── skills/ │ └── frontend-design/ │ └── SKILL.md ├── src/ ├── package.json └── README.md The important file here is: SKILL.md This is where we will put our instructions. Step 2: Write Your SKILL.md Open the file: code .claude/skills/frontend-design/SKILL.md Now add the following: --- name : frontend-design description : Build clean, responsive frontend UI with simple and consistent design rules. --- # Frontend Design Rules Before writing UI code: 1. Understand the purpose of the page. 2.
AI 资讯
Connect a Carrd Landing Page to Payhip Without Building a Backend
Affiliate disclosure: I’m an independent Payhip Partner. The optional signup link at the end is my partner link; I may receive a commission from Payhip if a referred seller generates eligible revenue. I am not a Payhip employee or official representative. A creator selling one template or downloadable guide does not need to write a payment backend. The safer architecture is usually: Carrd or static page ↓ Payhip product page or direct checkout ↓ Hosted payment and product delivery Your public page explains the offer. The hosted commerce platform owns the payment flow. No card data, secret keys, or payment logic belongs in Carrd. This tutorial shows two link-based integrations and one optional embed route. Before you start You need: A published product in Payhip Its public product URL A button on your Carrd or static page A clear product description, support contact, and terms In Payhip, the product URL is available from the product’s Share / Embed controls. A typical product URL has this shape: https://payhip.com/b/PRODUCT_KEY Use your real product key in every example below. Option 1: Send visitors to the product page This is the safest default when the buyer still needs details before purchasing. In Carrd: Select the call-to-action button. Set its URL to your full Payhip product URL. Use a descriptive label such as View template details or See what’s included . Preview the page on desktop and mobile. On a conventional static site, the equivalent HTML is just an anchor: <a class= "product-button" href= "https://payhip.com/b/PRODUCT_KEY" > View product details </a> No JavaScript is required. Use this route when the Payhip product page contains important previews, license terms, compatibility notes, or variations that do not fit on your landing page. Option 2: Link directly to checkout If your landing page already gives the buyer everything needed to decide, a direct checkout removes an intermediate page. Payhip documents this URL format: https://payhip.com/buy?link=
开发者
Making a screenshot PDF searchable — no OCR, because we rendered the page
We archive whole web pages as PDFs. Under the hood each page is a full-height screenshot dropped onto a PDF page — which looks perfect and is completely useless the moment you want to use the text. Ctrl+F finds nothing. You can't copy a sentence. A screen reader opens the document and sees… an empty page with one big image. The fix is the same trick a "searchable scan" uses: draw the real text invisibly , on top of the image, at the exact coordinates where each word appears. The difference is that a scanner needs OCR to guess the text — we rendered the page ourselves , so we already have the ground truth. No OCR, no guessing. Here's how we built it with pdf-lib and @pdf-lib/fontkit , and the one part that turned out to be genuinely hard. The shape of it While the page is still open in the headless browser, ask the DOM where every word is. Assemble the PDF: embed the screenshot as the page background. For each word, drawText it at its coordinates with opacity: 0 . Steps 1 and 3 are easy. The trap is in which words you're allowed to draw. Step 1 — ask the browser where the words are Running inside the page (Puppeteer's page.evaluate ), we walk every text node and measure each word with a Range : const walker = document . createTreeWalker ( document . body , NodeFilter . SHOW_TEXT ); // ...for each word in each text node: const range = document . createRange (); range . setStart ( node , start ); range . setEnd ( node , end ); const rects = range . getClientRects (); if ( ! rects . length ) continue ; // display:none or empty line box const b = rects [ 0 ]; // first rect = where the word starts out . push ({ t : word , x : b . left + window . scrollX , // document coordinates, not viewport y : b . top + window . scrollY , w : b . width , h : b . height , fs : parseFloat ( getComputedStyle ( el ). fontSize ) || 12 , }); getClientRects() gives viewport coordinates, so we add scrollX/scrollY to get document coordinates — the ones that line up with a full-page screenshot.
AI 资讯
WebMCP Agentic Web: Debugging 2‑Second Latency Spikes
webmcp agentic web: Why Backend Engineers Must Rethink Their Architecture Quick Answer webmcp agentic web: Agentic web workloads over MCP require stateless gateways, distributed context stores, prompt caching, and fine‑grained telemetry to keep latency below 350 ms and cost under control. Latency and State in Multi‑Agent LLMs When a Multi‑Agent System talks to an LLM over the Model Context Protocol (MCP) , the assumptions that hold for CRUD REST APIs break apart. A 200‑ms timeout that covers a simple GET request now collapses into a 2‑second latency spike because each tool call injects a new sub‑prompt, inflates the token budget, and forces the backend to stitch together dozens of partial contexts. In the field, the LLM behaves like a stateful, high‑throughput service that must be orchestrated, not a stateless function. Real‑World Example Consider a U.S. e‑commerce platform that needs to serve 12 k concurrent shopping sessions. Each session spawns up to five agents (pricing, inventory, recommendation, fraud, checkout). The platform’s existing micro‑service stack was built for single‑shot CRUD calls; when the agentic layer was added, the following issues surfaced: Context drift: stale prompts silently degraded recommendation quality. Token explosion: every tool call added 200–300 tokens, pushing the total payload past 8 k tokens. Throughput hit: the MCP service was throttled by Azure OpenAI’s per‑deployment request rate limits. After re‑architecting to a stateless MCP gateway backed by a distributed context store, the platform maintained 99th‑percentile latency under 350 ms even during a Black Friday surge. Trade‑Offs Aspect Option A Option B When to choose Context Storage Redis Cluster (in‑memory, low latency) Cosmos DB (strong consistency, global replication) Redis for ultra‑low latency, Cosmos for compliance or multi‑region writes Prompt Caching Enable KV‑cache on Azure OpenAI Re‑send system prompt on every request Enable when prompt size >20% of total token budge
AI 资讯
How to Convert PDF to Word in the Browser with Vue 3 and pdf-lib
Converting PDF to Word seems straightforward, but the reality is more complex. PDF stores text as character coordinates, while Word uses structured paragraphs. Bridging this gap requires careful text extraction and order reconstruction. Here's how to build a browser-based PDF to Word converter with Vue 3 and pdf-lib . The challenge: PDF vs Word PDF is a presentation format — text is positioned precisely on the page. Word is an editing format — text flows in paragraphs with styles. Converting between them means: Extracting text from PDF coordinates Reconstructing reading order Generating structured DOCX output The stack Vue 3 with Composition API pdf-lib for PDF parsing docx for Word document generation Vite for bundling The core implementation < script setup lang= "ts" > import { ref } from ' vue ' import { PDFDocument } from ' pdf-lib ' import { Document , Paragraph , TextRun } from ' docx ' const file = ref < File | null > ( null ) const processing = ref ( false ) const result = ref < Blob | null > ( null ) async function convertPdfToWord () { if ( ! file . value ) return processing . value = true const arrayBuffer = await file . value . arrayBuffer () const pdf = await PDFDocument . load ( arrayBuffer ) const pages = pdf . getPages () const allChunks : TextChunk [] = [] for ( const page of pages ) { const textContent = await page . getTextContent () for ( const item of textContent . items ) { allChunks . push ({ text : item . text , x : item . transform [ 4 ], y : item . transform [ 5 ], size : item . size }) } } // Sort by reading order const sorted = sortByReadingOrder ( allChunks ) // Generate DOCX const doc = new Document ({ sections : [{ properties : {}, children : sorted . map ( chunk => new Paragraph ({ children : [ new TextRun ( chunk . text )] }) ) }] }) const blob = await doc . pack () result . value = blob processing . value = false } interface TextChunk { text : string x : number y : number size : number } function sortByReadingOrder ( chunks : TextCh
AI 资讯
Next.js 16.3: Instant Navigations, Up to 90% Less Dev Memory and Faster Builds
Vercel has released Next.js 16.3, featuring significant updates since version 16.0. Enhancements include reduced memory usage during development, accelerated build times, and improved type checking. Instant Navigations introduces faster, client-like responses while maintaining server-rendered architecture. Developers are advised to gradually adopt new features due to noted caveats. By Daniel Curtis
AI 资讯
Calling a TypeScript Backend Without Integration Code - A Simple Task Tracker with Graftcode
Most developers building frontend applications spend a lot of time writing code that communicates with their backend due to the traditional approach (using APIs). This is not because the logic is hard to implement, but because the communication itself is complex. When using standard APIs, we build routes, define request and response models, generate clients, and keep multiple layers on track with application updates. Instead of exposing backend functionality through REST endpoints and consuming it through HTTP clients, Graftcode exposes backend methods directly and generates packages that applications can install and use as dependencies. The result is a communication model that is like you are calling a library rather than consuming an API with strongly typed clients. Working with Graftcode is very simple: install your library and call its functions. In this article, we'll be building a simple task tracker or to-do list application using React and a TypeScript backend to see what working with Graftcode looks like. In this blog post, we will learn the following: Why API layers require you to maintain APIs manually How Graftcode exposes backend functionality through Graftcode Gateway How Graftcode Vision helps discover backend capabilities Familiarity with APIs and fetch() requests How React applications can use TypeScript backend logic without building API routes Why strongly-typed backend packages can improve developer experience Prerequisites Let’s get our hands a bit dirty, but before we do, there are some need-to-haves to get you started. Let’s have a look at that in this section: Latest Node version installed on your machine Basic knowledge of React and TypeScript Familiarity with how APIs and fetch requests work (for understanding how easy Graftcode’s approach is) A Graftcode account Graftcode gateway installed on your local machine With these prerequisites, you’ll first understand why most to-do list applications rely heavily on APIs for their logic and what c
开发者
React useEventListener Hook: Type-Safe DOM Events (2026)
Here's a modal close-on-Escape that quietly does the wrong thing: function Modal ({ onClose }: { onClose : () => void }) { useEffect (() => { const onKey = ( e : KeyboardEvent ) => { if ( e . key === " Escape " ) onClose (); }; window . addEventListener ( " keydown " , onKey ); return () => window . removeEventListener ( " keydown " , onKey ); }, [ onClose ]); return < div role = "dialog" > … </ div >; } If the parent passes an inline onClose={() => setOpen(false)} — and it almost always does — onClose is a new function on every render, so this effect tears the listener down and adds a fresh one on every single render of the parent. Drop onClose from the deps to stop the churn and you get the other bug: the listener now holds the first render's onClose forever, and closing the modal calls a stale closure. You can't win this with a dependency array, because the two things you want are in direct conflict: subscribe once , but always run the newest handler . The fix is to separate them — register the listener on a stable identity, and call through a ref that's kept current. useEventListener from @reactuses/core is that split, packaged. This post covers what it actually does under the hood, the four ways to name a target, exactly what TypeScript infers for each one (this part surprises people), the options that don't retrigger, and the two gotchas worth knowing before you ship it. Quick Start npm install @reactuses/core import { useEventListener } from " @reactuses/core " ; function Modal ({ onClose }: { onClose : () => void }) { useEventListener ( " keydown " , ( e ) => { if ( e . key === " Escape " ) onClose (); }); return < div role = "dialog" > … </ div >; } That's the whole fix. No dependency array, no useCallback on the parent, no cleanup to remember. The listener is added to window once when the component mounts and removed when it unmounts; the arrow function you passed is re-created on every render and it doesn't matter, because the listener never re-registers
AI 资讯
Stop Writing Regex to Match URLs — The Browser Already Can
Priya was three paragraphs into rewriting a support ticket when the page flashed and her draft reverted to what it had looked like an hour earlier. She hadn't refreshed. Nobody had. The service worker had. It was running a cache-first strategy for ticket pages — fetch once, serve from cache after that, so the dashboard felt instant on a flaky connection. The intent was to cache /tickets/482 , the read-only view, and leave /tickets/482/edit alone, since an edit form is exactly the page you never want served stale. Here's the line that decided which was which: const isTicketView = /^ \/ tickets \/\d +/ . test ( pathname ); Spot it yet? Read it once more before you scroll. The missing character was $ /^\/tickets\/\d+/ anchors the start of the string — ^ — but never anchors the end. So it matches /tickets/482 . It also matches /tickets/482/edit , /tickets/482/history , and /tickets/482-anything-at-all , because "one or more digits after /tickets/ " is true of all of them. The regex was never wrong about what it checked. It just never checked enough. The one-character fix is obvious once you see it: const isTicketView = /^ \/ tickets \/\d +$/ . test ( pathname ); Ship that and you'll hit the next edge case within a week: a trailing slash ( /tickets/482/ ) now fails to match, because $ demands nothing comes after the digits — not even a slash. Add \/? before the $ and you've fixed that one. Then someone deep-links to /tickets/482?tab=history and the query string breaks the anchor again, because pathname on some code paths actually holds the full URL. Each fix is a patch on the last, and every patch is a chance to reintroduce the first bug in a new shape. This is the part nobody tells you about hand-rolled URL matching: it isn't hard because regex is hard. It's hard because "does this path match this shape" has a dozen boundary conditions, and a hand-written pattern only encodes the ones you happened to think of on the day you wrote it. The API built for exactly this job T
AI 资讯
Dashforge: an application orchestrator for React
React solved rendering. Dashforge tries to solve orchestration — theming, forms, permissions, and visibility moved out of your components, declaratively, predictably, reusably. Two skins (MUI and Tailwind), one contract. Building complex applications isn't about building components. Inside a single module you're juggling forms, permissions, roles, visibility conditions, fields that depend on other fields, business logic. And all that logic ends up scattered across the app : a <Controller> here, an if (user.role === …) there, a useEffect watching one field to update another, a context for theming. If React solves the rendering problem, Dashforge tries to solve the orchestration problem. Dashforge moves that complexity out of the components and makes it declarative, predictable, and reusable . At its core it uses react-hook-form ; on top of it, a stable contract — identical across the MUI and Tailwind editions. Let's go through it piece by piece. 1. Theming — token-first, build-time and run-time Components don't hard-code colors or spacing: they consume typed design tokens ( @dashforge/tw-tokens , a pure TypeScript package, zero runtime). From there, the tokens travel on two rails. Build-time — the utilities. A Tailwind preset emits the usual utilities ( bg-primary-600 , text-neutral-900 ): // tailwind.config.ts import { dashforgePreset } from ' @dashforge/tw-theme ' ; export default { presets : [ dashforgePreset ()], content : [ ' ./src/**/*.{ts,tsx} ' ] }; Run-time — the CSS variables. The provider republishes those same tokens as CSS variables on <html> : < DashforgeTailwindProvider > < App /> </ DashforgeTailwindProvider > Here's the trick: bg-primary-600 doesn't resolve to a fixed color — it resolves to var(--tw-color-primary-500) . The provider sets that variable; change the variable, the color changes — no re-render, no Tailwind rebuild. The store is reactive (Valtio) with cross-tab sync, so dark mode or a live theme change is just a variable flip. In the MUI e