今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

标签:#node

找到 103 篇相关文章

AI 资讯

Building LIA (Part 1 Implementation): Clean Architecture and Argon2id in a Real Fastify + Prisma Registration Flow

LIA is a hyperlocal employability platform I'm building for an isolated coastal district in Brazil — think fixed retail jobs, gigs, and a reputation layer, all matched by proximity instead of routed through a national job board. This post is about the implementation: the actual folder structure, the real RegisterUserUseCase, and the Argon2id decision — pulled straight from the repository, not reconstructed from memory. The Clean Architecture folder structure LIA's backend is organized in four layers, and the direction of dependency is non-negotiable: outer layers depend on inner layers, never the other way around. backend/src/ ├── domain/ │ ├── entities/ │ └── repositories/ # interfaces only ├── application/ │ ├── dto/ │ └── use-cases/ ├── infrastructure/ │ ├── database/ │ └── repositories/ # Prisma implementations ├── presentation/ │ ├── controllers/ │ └── routes/ └── shared/ └── errors/ Let's walk through the registration feature end to end, following that exact order. Domain — the entity and the repository contract The User entity is a plain interface. No decorators, no ORM annotations, no framework leaking in: typescript// domain/entities/user.ts export interface User { id: string; name: string; email: string; password: string; createdAt: Date; updatedAt: Date; } The repository is defined as a contract, not an implementation. The domain doesn't know — and doesn't care — whether it's backed by PostgreSQL, an in-memory map, or something else entirely: typescript// domain/repositories/user.repository.ts import { RegisterUserDTO } from '../../application/dto/register-user.dto.js'; export interface UserRepository { create(data: RegisterUserDTO): Promise<{ id: string; name: string; email: string; createdAt: Date; updatedAt: Date; }>; findByEmail(email: string): Promise<{ id: string; name: string; email: string; password: string; createdAt: Date; updatedAt: Date; } | null>; } Notice create() never returns the password hash. That's not an accident — it's the same "strip

2026-07-15 原文 →
AI 资讯

Production-Ready AI Agents in Node.js: Iteration Caps and Tracing

Your AI Agent Needs Tracing, Not Just Logs You've probably already called an LLM from a Node.js backend. That part's easy — every provider ships a solid SDK. The part that actually trips people up is what happens after : turning that one API call into an agent that reasons, uses tools, loops a few times, and still behaves once real users are hitting it. Here's a small, honest pattern for that — plus the one thing most tutorials skip: making the loop debuggable. Why Node.js is doing this job Node has quietly become the default home for the application layer around AI. It's become the preferred middle layer for deploying modern AI agents, wrapping heavier model inference behind fast Node APIs. Python still owns training and the heavy orchestration frameworks — Node owns the gateway, the auth, the streaming UI, and the business logic wrapped around all of it. On the SDK side, things consolidated fast: OpenAI's Node SDK holds roughly a third of weekly npm downloads across the major JS AI SDKs, and Anthropic's TypeScript SDK has grown nearly tenfold in a year. And despite all the framework noise, most production teams just use the Claude or OpenAI SDK directly — reaching for LangChain.js or Mastra only once multi-agent coordination actually earns its keep. The loop: reason, act, repeat Almost every "agent" in 2026 runs on the same loop: reason about the task, act through a tool call, look at what came back, reason again — repeat until done. That's it. The engineering is in the guardrails around it, not the loop itself. // agent.js import Anthropic from " @anthropic-ai/sdk " ; const anthropic = new Anthropic (); // reads ANTHROPIC_API_KEY from env const tools = [ { name : " get_order_status " , description : " Look up the status of a customer order by order ID. " , input_schema : { type : " object " , properties : { orderId : { type : " string " } }, required : [ " orderId " ], }, }, ]; async function getOrderStatus ({ orderId }) { // stand-in for a real DB/service call r

2026-07-15 原文 →
AI 资讯

The Everyday Backend Engineer: Step 10 — The Observer Pattern

Welcome back to The Everyday Backend Engineer: Practical Design Patterns . In our last post, we made our core algorithms interchangeable using the Strategy Pattern. Today, we close out our design patterns roadmap with arguably the most native pattern in the entire Node.js ecosystem: The Observer Pattern . Let’s look at how to master event-driven decoupling to trigger secondary workflows seamlessly without bloat. 🔴 The Problem: Direct Inline Side-Effects Imagine you are writing a video processing engine or a simple order fulfillment system. When a specific event happens—such as an order being finalized—multiple unrelated departments want a piece of the action: The Notification Service needs to send an SMS and Email receipt. The Logistics Service needs to generate a warehouse fulfillment ticket. The Analytics Service needs to update marketing tracking boards. If you don't decouple these events, your primary execution service ends up managing a giant web of secondary micro-services: // ❌ Bad Practice: The primary service is drowning in secondary dependencies const EmailService = require ( ' ../services/email ' ); const WarehouseService = require ( ' ../services/warehouse ' ); const AnalyticsTracker = require ( ' ../services/analytics ' ); class OrderProcessor { async finalizeOrder ( order ) { console . log ( " Saving primary order to the database... " ); // Core business logic ends here // The codebase smell: Procedural cascading dependencies await EmailService . sendReceipt ( order . userEmail ); await WarehouseService . createShipment ( order . id ); await AnalyticsTracker . trackSale ( order . totalAmount ); } } module . exports = OrderProcessor ; Why does this slow your system down? Your core OrderProcessor is now structurally dependent on three separate systems. If the AnalyticsTracker throws a network timeout error or if the warehouse API changes its interface, your core transaction fails or hangs. Furthermore, adding a fourth side-effect (like an auditing logger

2026-07-14 原文 →
AI 资讯

Node.js Hackathon Backends: From Idea to Demo in Under an Hour

Hackathons are intense. You've got a brilliant idea, a tight deadline, and often, limited sleep. The last thing you want is to spend half your precious time wrestling with database boilerplate, ORM setup, or SQL query syntax. This guide will walk you through building a functional Node.js backend for your hackathon project, focusing on speed and minimal friction, so you can spend more time on your core idea. The Hackathon Backend Challenge Typically, setting up a database and its interaction layer involves several steps: Schema Definition: Deciding on tables/collections, fields, types, and relationships. ORM/Driver Setup: Installing and configuring your database driver or ORM (e.g., Mongoose, Sequelize). Model Creation: Translating your schema into code, often with verbose syntax. Query Writing: Crafting SELECT , INSERT , UPDATE , DELETE statements or ORM methods for every data operation. Debugging: Fixing typos, schema mismatches, and complex join logic. This process, while fundamental, eats up valuable time that could be spent on features, UI, or even sleep. For a hackathon, you need to iterate rapidly, and database interactions should be the least of your worries. Strategy 1: Embrace Simplicity For many hackathon projects, you don't need highly optimized, production-grade queries from day one. You need functional queries that work quickly. Focus on getting data in and out reliably. Strategy 2: Natural Language for Data Modeling Instead of writing verbose schema definitions, think about how you'd describe your data to a non-technical person. For example, if you're building a task management app, you might say: "We need a collection of tasks. Each task has a title, a description, a due date, and a status (like 'pending' or 'completed'). Each task belongs to one user." This natural language description contains all the essential information for a data model, including relationships and field types. Strategy 3: Expressive Querying Similarly, when you need to fetch dat

2026-07-13 原文 →
AI 资讯

You reach for `Promise.all` for every concurrent request. Here's when to use the other three.

Imagine you're loading a dashboard. Four widgets, four APIs, fire them all at once: const [ users , revenue , alerts , activity ] = await Promise . all ([ fetchUsers (), fetchRevenue (), fetchAlerts (), fetchActivity (), ]); The alerts API is occasionally slow and sometimes returns a 500. When it does, your entire dashboard fails. Not one broken widget — four broken widgets. Promise.all rejects on the first failure and takes the other three successful results with it into the void. You reached for the right primitive for concurrency, but the wrong one for this use case. The four methods and what they actually do JavaScript gives you four ways to run promises concurrently. They differ in one thing: what happens when a promise fails or resolves first. Method Resolves when Rejects when Promise.all All succeed Any one fails Promise.allSettled All finish (success or failure) Never Promise.any Any one succeeds All fail Promise.race Any one finishes Any one fails first The instinct to reach for Promise.all is understandable — it returns all the values in a single array and feels like the obvious way to "do these things at the same time." But concurrency and failure handling are two separate questions. Promise.all answers both at once, and the answer to the second one is often wrong for the situation you're in. 🎮 Try it yourself ▶️ Open the interactive playground → Runs right in your browser — poke at it and watch the concept react live. Promise.allSettled — partial success Promise.allSettled waits for every promise to settle — resolve or reject — and returns a result array describing what happened to each one: const results = await Promise . allSettled ([ fetchUsers (), fetchRevenue (), fetchAlerts (), fetchActivity (), ]); for ( const result of results ) { if ( result . status === ' fulfilled ' ) { console . log ( ' got data: ' , result . value ); } else { console . error ( ' failed: ' , result . reason ); } } Each element has a status of 'fulfilled' (with a value ) or 'r

2026-07-13 原文 →
AI 资讯

Failure Engineering Explained by Uncle to Nephew — Episode 2: Types of Failures

Episode 1 established the mindset: failure is normal, not a sign of bad engineering. Episode 2 gets specific — you can't detect or handle a failure you can't even name. Saturday, Round 2 👦 Nephew: Uncle, last time you convinced me failure is basically guaranteed. Fine, I accept it. So what actually fails ? 👨‍🦳 Uncle: You tell me. Start listing things that could go wrong in your app right now. 👦 Nephew: Uh... the server could crash. The database could go down. My code could have a bug. 👨‍🦳 Uncle: Keep going. 👦 Nephew: The network? Someone could deploy the wrong thing? Payment gateway dies mid-checkout? 👨‍🦳 Uncle: You just named six of the seven categories without trying. You already know this. You've just never sorted it. 1. Hardware Failure 2. Software Failure 3. Network Failure 4. Database Failure 5. Third-Party Failure 6. Human Error 7. Resource Exhaustion 👦 Nephew: Then why do we need the list at all, if I already know it instinctively? 👨‍🦳 Uncle: Because "instinctively" isn't fast enough at 2 AM. Let's trace each one properly. Part 1 — Hardware Failure 👦 Nephew: This one's obvious anyway — I deploy to AWS. The cloud hides hardware failure from me. 👨‍🦳 Uncle: Does it? 👦 Nephew: ...doesn't it? That's the whole point of paying for EC2 instead of buying a server. 👨‍🦳 Uncle: Let's trace it. Your app sits on an EC2 instance. What's underneath the instance? 👦 Nephew: Virtual machine stuff, I guess? 👨‍🦳 Uncle: And underneath that ? 👦 Nephew: ...an actual physical machine somewhere. In a data center. 👨‍🦳 Uncle: There it is. Your app | "Virtual" server (EC2/Droplet) | ACTUAL physical hardware somewhere in a data center | Still capable of failing — just less visible to you 👦 Nephew: So it's not hidden. It's just one layer further away than I thought. 👨‍🦳 Uncle: Exactly. AWS absorbs a lot of it — that's part of what you're paying for — but disks still fail, instances still get abruptly terminated, whole availability zones still go down. That's Hardware Failure . Hardware Fa

2026-07-12 原文 →
AI 资讯

Shipping Async Video Background Removal at $0.10/sec

Why async matters for video I've been running useKnockout - a background removal API that processes images in ~200ms - for a few months. Images are fast enough to handle synchronously: POST a file, wait 200ms, get a PNG back. Video is different. Even a 5-second clip at 30fps is 150 frames. At 200ms per frame, that's 30 seconds of processing. You can't hold an HTTP connection open for 30 seconds and call it a good API. So today I shipped POST /video/remove - async video background removal that returns a job ID immediately, processes in the background, and gives you ProRes 4444 (RGB+alpha) when it's done. What shipped As of v0.11.0 (July 10, 2026): POST /video/remove - upload a video, get a job ID back GET /jobs/{job_id} - poll for status, download the result when ready ProRes 4444 output - RGB with full alpha channel, ready to drop into Premiere/Final Cut/DaVinci Node SDK videoRemove() and getJob() in v0.7.0 Python SDK video_remove() and get_job() in v0.7.0 Billing is a dedicated video.seconds meter at $0.10/sec (different from the per-image rate), with a 15-second cap to keep costs predictable. How to use it (Node SDK) import { useKnockout } from ' useknockout-node ' ; import fs from ' fs ' ; const client = useKnockout ({ apiKey : process . env . KNOCKOUT_API_KEY }); // Submit the video const job = await client . videoRemove ({ file : fs . createReadStream ( ' ./input.mp4 ' ) }); console . log ( ' Job ID: ' , job . id ); // Poll until done let status = await client . getJob ( job . id ); while ( status . status === ' processing ' ) { await new Promise ( resolve => setTimeout ( resolve , 2000 )); status = await client . getJob ( job . id ); } if ( status . status === ' completed ' ) { // Download the ProRes 4444 result const video = await fetch ( status . result_url ); const buffer = await video . arrayBuffer (); fs . writeFileSync ( ' ./output.mov ' , Buffer . from ( buffer )); } The job object includes duration_seconds (billed amount), status ( processing / complet

2026-07-12 原文 →
AI 资讯

How to clone a Keycloak realm on the same instance (fixing "duplicate key value violates unique constraint")

If you've ever tried to duplicate a Keycloak realm on the same server — say, to spin up a myrealm-dev realm alongside your existing myrealm — you've probably hit this wall: Export the realm from the Admin Console ( Realm settings → Action → Partial export , with clients and groups/roles included). Rename it in a text editor, or in the import dialog's "realm name" field. Import it back into the same Keycloak instance. Watch it fail with: ERROR: duplicate key value violates unique constraint "constraint_a" Detail: Key (id)=(51e1a26d-c24f-4454-9a34-708f1fc14917) already exists. Why this happens A realm export isn't just configuration — it's a snapshot of database rows. Every role, client, user, protocol mapper, component, and authentication flow in the export carries the same internal UUID it has in the live database. Renaming the realm field changes what the realm is called , but it does nothing to the dozens (often hundreds) of UUIDs referenced throughout the file. Import that JSON into the instance it came from, and Keycloak tries to insert rows whose primary keys already exist. Every single one collides. This is a known limitation, tracked upstream as keycloak/keycloak#24770 . Keycloak's exporter was never designed to produce an import-anywhere-including-here artifact — it assumes you're moving the realm to a different instance (dev → staging → prod), where the UUID space is independent. The manual fix (and why it doesn't scale) In principle you can fix this by hand: open the export JSON, find every UUID, and replace it with a fresh one, while keeping track of which old UUID maps to which new UUID so that references between objects (a role's containerId , a client's serviceAccountClientId , a flow's execution list) still point at the right thing after the rewrite. For a small realm with a handful of clients this is tedious but doable in an editor with careful find-and-replace. For a realm with custom roles, several clients, an identity provider, and a full set of a

2026-07-11 原文 →
开发者

A Beginner's Guide to Installing and Using Node.js on Windows

Have you ever wondered how massive modern platforms like Netflix, PayPal, and LinkedIn handle millions of users simultaneously without crashing? The secret weapon behind much of the modern web is Node.js. Traditionally, JavaScript—the language that makes websites interactive—could only run inside a web browser like Chrome or Edge. Node.js changed the game by freeing JavaScript from the browser, allowing it to run directly on your computer. This means you can use it to build backend servers, automate boring computer tasks, or run powerful development tools. If you are intimidated by coding, don't worry. This guide will take you from zero to running your very first Node.js program on Windows, step-by-step. Prerequisites Before we begin, you only need two things: A computer running Windows 10 or 11. An active internet connection to download the installer. No prior coding experience or command-line knowledge is required! Step-by-Step Instructions Download the Node.js Installer First, we need to grab the official installation file. Open your web browser and go to the official website: nodejs.org. You will see two primary options to download. Always choose the LTS (Long Term Support) version. The LTS version is heavily tested, stable, and less likely to give you unexpected errors. Click the Windows Installer button to download the .msi file to your computer. Run the Setup Wizard Once the download finishes, navigate to your Downloads folder and double-click the file to open the setup wizard. Click Next on the welcome screen. Accept the license agreement and click Next. Leave the default installation folder as it is (C:\Program Files\nodejs) and click Next. On the "Custom Setup" screen, leave everything at its default and click Next. Important Step: You will see a checkbox that asks to "Automatically install the necessary tools." Leave this unchecked for now to keep your setup simple and fast. Click Next. Finally, click Install. If Windows asks for permission to make change

2026-07-11 原文 →
AI 资讯

Building a Fully Automated Facebook Post Scheduler using Node.js and GitHub Actions

How I Built a Zero-Cost Facebook Auto-Poster Using Node.js and GitHub Actions Automating social media management can save hours of manual work. In this guide, I will show you how to build a fully automated, production-ready system that posts daily motivational quotes with images to a Facebook Page— completely for free , running on autopilot via GitHub Actions. We will also tackle a major pain point: resolving Meta's strict token expiration and permission structures by dynamically fetching a Page Access Token using a Meta Business System User, the officially recommended way for secure automation. 🛠️ Prerequisites Before diving into the code, make sure you have: A Facebook Page A Meta Developer Account A Meta Business Suite (Business Portfolio) A GitHub Account Basic knowledge of Node.js 🎯 Step 1: Configuring Meta Architecture for Secure Automation Meta has deprecated direct publish_actions for user tokens, making automated image uploads tricky. The professional way to solve this is by using a System User bound to a Business Portfolio . 1. Create a Meta App Go to the Meta for Developers dashboard. Create a new app, choose Business and pages as the category, and give it a clean name. 2. Link your Facebook Page Inside your App Dashboard, navigate to App Settings -> Advanced . Scroll down to the App Page section and select your target Facebook Page to link it. 3. Setup a System User Go to your Meta Business Settings ( business.facebook.com/settings ). Under Users , click on System Users and create an Admin System User (e.g., Ttp-penguin ). Click Assign Assets , select your Facebook Page, and turn on the Full Control (Everything) toggle. 4. Generate the Permanent Token Click Generate Token for that System User and select your app. Explicitly check these 3 essential scopes : pages_manage_posts pages_read_engagement pages_show_list Copy the generated token ( EAak2B... ). Save this safely —this token acts as our master key! 💻 Step 2: Writing the Automation Script We will wri

2026-07-11 原文 →
AI 资讯

Node.js Internals Explained by Uncle to Nephew — Part 4: Express Plumbing, Error Handling & The Full Roadmap

Bonus round. Parts 1–3 covered why Node exists, what's happening inside it, and the full request journey. This part mops up the pieces that didn't fit anywhere else — the Express plumbing, error handling, and a checklist to test yourself against. Saturday, Round 4 Nephew: Uncle, one more round? I promise this is the last one for a while. Uncle: pours chai — you said that last time too. Fine, what's bugging you now? Nephew: Small things, actually. express.json() , cookie-parser , express.Router() — I use all of them, copy-pasted from old projects, but I couldn't explain any of them if you asked me directly. Uncle: That's exactly the right instinct — the things you copy-paste without understanding are always the things that break at 2 AM. Let's fix that. Part 4.1 — Two Directions Node Never Confuses Uncle: Before plumbing, one small but important idea that ties Parts 2 and 3 together. Everything Node does falls into exactly two directions . DIRECTION 1 — Incoming Events "The outside world is telling Node something happened" OS → libuv → Event Loop → Your JavaScript Examples: HTTP request arrives, TCP connection opens, WebSocket message arrives DIRECTION 2 — Outgoing Async Operations "Your JavaScript is asking Node to go do something" JavaScript → libuv → Worker Thread → OS → Disk/DB ↓ result comes back through libuv → Event Loop → your callback Examples: fs.readFile(), crypto.pbkdf2(), dns.lookup() Nephew: So an incoming HTTP request and a fs.readFile() call both eventually pass through libuv and the event loop — but they enter from completely opposite directions? Uncle: Exactly. One is the world pushing something at Node. The other is Node reaching out to go get something. Same event loop handles both, but the journey to get there is different — an HTTP request never touches the thread pool; a file read almost always does. Incoming HTTP Request: File Reading: Browser JavaScript | | OS libuv | | libuv Worker Thread | | Event Loop Operating System | | JavaScript Disk |

2026-07-10 原文 →
AI 资讯

Stop Triaging. Start Fixing. Introducing VigilOps

You've seen the alert. You've opened the PR. You've read the changelog. Then you realize: your code doesn't even call the vulnerable function. Every week. Hundreds of teams drowning in CVE notifications for packages sitting dormant in their node_modules — dependencies they pulled in years ago, bundled by a transitive library, and never actually executed. Meanwhile, the real vulnerabilities get buried. VigilOps is a free Node.js CLI that fixes this. How VigilOps Works VigilOps does three things: Scans dependencies against OSV.dev — the open vulnerability database used by GitHub, PyPI, and npm Runs static reachability analysis to filter out unreachable vulnerabilities (packages in your tree but never called by your code) Auto-opens a GitHub PR with the fix The result: you get one PR with one real vulnerability. Not a spreadsheet. Not a wall of Slack messages. A fix. Demo Here's a quick scan: npx vigilops scan examples/vigilops-demo-lodash And to see everything including suppressed (unreachable) deps: npx vigilops scan examples/vigilops-demo-express --all The --all flag shows what's in your dependency tree but not actually reachable from your code. That's what the noise looks like — and that's what VigilOps filters out. Why This Is Different Dependabot and Snyk scan your entire lockfile. They report every CVE in every package, regardless of whether your code ever touches the vulnerable surface. This creates alert fatigue that causes teams to eventually... stop reading. VigilOps inverts the model: only surface vulnerabilities in code you actually call. Dependabot: "Your project has 47 vulnerabilities" (but 40 are unreachable noise) VigilOps: "Your project has 1 reachable vulnerability. PR is ready." Quick Start npm install -g vigilops npx vigilops scan . Authenticate with GitHub: https://github.com/Vigilops/vigilops npx vigilops auth That's it. The first run will scan, analyze, and open a PR if there's a fixable reachable vulnerability. What's Included OSV.dev integrati

2026-07-10 原文 →
AI 资讯

I'm Building Claude Basecamp — an Open-Source OS for Everything Claude Code (and I Need Help)

Quick confession: this started as "let me stop babysitting my tests and just make them stay green," and it turned into something a lot bigger. I want to be upfront about where I'm actually trying to take it. I built Claude Basecamp, and as of today it's open source. The reconciliation loop (declare "tests always green," it holds that true) is the part you'll notice first, but it's not really the point. The point is I want this to become the operating system for everything you do with Claude Code, one place that knows about every repo, every session, every routine, every connector, every skill, and every mistake it's ever made, instead of all of that living scattered across terminal windows and dead transcripts. Right now it already covers a decent chunk of that: npx claude-basecamp No install, no config. It finds the projects Claude Code already knows about and opens at http://localhost:4747 . Standing checks , the reconciliation loop. "Tests always green," "dependencies current," "the README documents every CLI flag" — say it once, Basecamp keeps it true, dispatches a fix run when it drifts, and only bugs you for the decisions that actually need a human. Reflexes. It goes back through your old transcripts, finds every time you said "no, don't do that," and turns it into a standing memory that every Claude Code session on your machine checks before touching Bash, Write, or Edit. A mistake made once doesn't get to happen a third time. Session Rescue. Resumes the actual dead session, same session ID, full context, when Claude Code dies mid-task, instead of starting over from scratch. A manager for every repo you just talk to: "keep the tests green," "track this goal," "what's the state of this repo?" Plus routines, background runs, an activity feed, stats, GitHub issue and PR hooks, notifications, webhooks, and a one-click catalog for connectors and skills. That's where it is today. What I actually want it to become is the default place you open whenever you're workin

2026-07-10 原文 →
AI 资讯

I Open-Sourced Claude Basecamp — Come Help Me Build a Reconciliation Loop for Claude Code

Kubernetes changed infrastructure forever with one idea: you declare desired state, and the system continuously reconciles reality to match it. I wanted that for my codebase, so I built Claude Basecamp and I'm open-sourcing it today. If you're running Claude Code across more than one repo, I'd genuinely love for you to try it, break it, and help me build it out. Try it in one command npx claude-basecamp No install, no database, no config. It discovers the projects Claude Code already knows about and opens at http://localhost:4747 . Runs on macOS, Linux, and Windows. What it does Standing checks, the reconciliation loop. Declare what must always be true, and Basecamp holds it: tests always green -> runs your suite on a cadence; failures dispatch a fix run that commits dependencies current -> npm outdated; safe updates applied, majors escalated to you issue backlog triaged -> gh-powered labeling and stale-closing anything in plain English -> "the README documents every CLI flag" checked read-only, fixed on drift Checks run against deterministic local facts (your real test suite, real npm outdated) wherever possible, zero tokens spent checking. Drift launches a bounded, budgeted, approval-gated convergence run. Repeated failure escalates to a decision card on Home instead of retrying forever. Reflexes, an immune system for your AI. Basecamp mines every transcript for the moments you pushed back (interruptions, "no, don't", permission denials) and turns each into an antibody. Once armed, every Claude Code session on your machine consults that memory before every Bash/Write/Edit action, so a mistake made twice gets blocked machine-wide before it happens a third time. Session Rescue. Notices when a Claude Code session died mid-task and lets you resume the actual dead session, same session ID, full context, as a background run that finishes the job and commits. A persistent manager for every repo. Each project gets an agent with full Claude Code tools plus control over Bas

2026-07-10 原文 →
AI 资讯

The project file is the interface: letting AI agents drive a video editor

Last week I open sourced FableCut , a Premiere-style video editor that runs in the browser and that AI agents can operate. It hit the front page of Hacker News ( thread ), and the questions there made me realize the interesting part isn't the editor. It's one design decision: the project file is the interface. The usual way, and why I flipped it Most AI video tools hide the edit behind an API. You call addClip() , applyFilter() , and the tool owns the state. If you want a human to touch the result, you build a whole collaboration layer. FableCut does the opposite. The entire timeline lives in one JSON document, project.json : media, clips, tracks, keyframes, transitions, markers. The editor UI reads it. The export renders it. And anything that can write JSON can edit video: Claude Code through MCP, a Python script, jq , or you with a text editor. { "id" : "c_title" , "kind" : "text" , "track" : "V3" , "start" : 0 , "duration" : 2.2 , "props" : { "text" : "HANDMADE" , "font" : "Bebas Neue" , "glow" : 45 , "textAnim" : "letter-pop" } } That clip is a glowing kinetic caption. There is no API call that creates it. Writing it into the file IS creating it. SSE as a doorbell, not a data channel The first question on HN was "what's the benefit of SSE here?" Fair question, because the SSE channel does almost nothing, and that's the point. The server watches the project file with fs.watch , debounces 150ms, and pushes the literal string change to the browser. No payload. The browser re-fetches the project and re-renders. The whole mechanism is about 15 lines on a bare node:http server. Why not WebSockets? Because the data only flows one way. Everything that writes (the UI, an agent, a shell script) goes through REST or the filesystem. The browser only ever needs to hear "something changed, go look." An event with no payload can't arrive out of order, and a missed event costs nothing because the next fetch has the latest state anyway. The revision counter, or: how a human and

2026-07-09 原文 →
AI 资讯

Deploying a real-time multiplayer game on Railway

This post contains Railway referral links. If you sign up through one I get a bit of credit. I build Old Light , a real-time strategy game that runs in the browser. Claim stars, grow an economy, send fleets, all while other players and NPC empires do the same. The second a build finishes or a fleet lands, the server pushes it to every connected client over a WebSocket. That last part, a long-lived server holding an open socket, rules out most of the usual hosts. Here's what it ruled in. Why not Vercel or Netlify Serverless shines when your backend is stateless functions. It's the wrong shape the moment you need a socket that stays open: socket.io wants one process that lives for the whole session, and serverless boots per request and then freezes. You can bolt on a managed WebSocket service, but that's a second system to run and pay for. Railway runs your service as a normal long-lived process, so socket.io just connects. Fly.io does this too with more knobs to turn. I wanted to ship, so Railway won. Monorepo, two services Old Light is an npm workspaces monorepo: a shared types package, an Express plus TypeORM plus socket.io API, and a Vite web app served by a small Express server. On Railway that's two services on the same repo, each with its own root directory and build command, shared built first. They deploy as separate origins, so the web app reads the API's URL from VITE_API_URL . Vite bakes that in at build time, so it's a build variable, not a runtime one. Postgres is a plugin that injects DATABASE_URL , and production runs migrations rather than synchronize . WebSockets need nothing special until you run more than one instance, at which point you'd add a Redis socket.io adapter. I haven't left a single box yet. A healthcheck that stops version skew Two services don't go live at the same instant. Push a commit that touches both, the web finishes first, and for a minute your new frontend is calling API routes that don't exist yet. It 404s, then heals itself o

2026-07-09 原文 →
AI 资讯

I built a free tool to scan your package.json for API deprecations

While researching API changes I noticed something — Google Maps removed DirectionsService on May 1 2026 with no soft fallback. Calls just throw runtime errors after the deadline. Most developers won't know until something breaks. So I built DepRadar — paste your package.json, it checks your exact stack against known deprecations and shows only the ones affecting you, with severity, sunset dates, and migration links. Currently tracks 13 real deprecations across: Google Maps (DirectionsService, DistanceMatrixService removed) OpenAI (Realtime API Beta sunset) AWS SDK v2 (maintenance mode) Microsoft Actionable Messages (retired) moment.js, request package And more Free → depradar.netlify.app Open source → github.com/Ahmed889-code/depradar What deprecations am I missing from your stack?

2026-07-09 原文 →
AI 资讯

10 Useless NPM Packages You Didn't Know You Needed

We have all been there. You are staring at your screen late at night, trying to optimize a bundle size, or debugging an enterprise pipeline that has been failing for three hours straight. The mainstream development community constantly tells us to only install packages that are high performance, audited for security, and strictly necessary for production. But where is the fun in a perfectly clean node_modules folder? Sometimes, the ultimate way to level up your engineering workflow is to inject some absolute chaos into your dependencies. Why spend hours writing robust logic when you can install a library that brings pure irony to your terminal? Let us dive into ten packages that might look completely useless on the surface but are actually the most important modules you will ever encounter in your developer journey. 1. emoji-poop This NPM package lets you use the poop emoji in your output. The emoji is well required in most of the websites as the real fun begins when the site crashes and you can use this poop emoji to showcase the errors with an emoji. This will help the clients get a bit calm after seeing the emoji and the errors. Think about it from a psychological perspective: traditional red stack traces cause immediate client panic, but a well-placed graphical poop emoji introduces a masterclass in modern error mitigation. javascript // npm i emoji-poop const emoji = require('emoji-poop'); console.log(emoji) // 💩 2. thanos-js Who doesn't love Marvel, and Thanos being the strongest villain in the MCU? This package lets you delete files in Thanos fashion. Once you install and run it, it deletes 50% of your files, reducing your stress and giving you less codebase to work with. Yes, it deletes the files for those who are confused about what this package does. It uses fs.unlinkSync to delete the files. Deleting random files from .git would be absolutely evil, and Thanos would love to do it. Exactly half of the files are deleted. Each file is given a chance at random

2026-07-09 原文 →
AI 资讯

Ship a 'Go Live' button: OBS in, LL-HLS out, webhooks in between

TL;DR We're adding live streaming to a SaaS dashboard: a backend endpoint that creates a stream, OBS as the broadcaster over RTMPS, LL-HLS playback with hls.js, and a webhook handler that keeps the UI honest. Working "go live" flow in an afternoon. 📦 Code: github.com/USER/repo (replace before publishing) Webinars, coaching sessions, company town halls: sooner or later your product gets the "can users go live?" ticket. The hard parts (ingest servers, transcoding, CDN delivery) are exactly the parts you should not build. We'll use FastPix as the managed layer here; the same flow works nearly line-for-line on Mux, Cloudflare Stream, or api.video. What we're building: A backend endpoint that creates a live stream and returns a stream key An OBS setup broadcasters can follow in two minutes A viewer page playing LL-HLS with hls.js A webhook handler that flips the webinar between scheduled → live → ended 1. Create the stream server-side 🛠️ You need API credentials (Access Token ID + Secret Key). FastPix uses Basic auth on the server API. Node 20.x, plain fetch , no SDK required (though official Node.js/Python/Go/Ruby/PHP/Java/C# SDKs exist if you prefer). // server/routes/streams.js import { Router } from " express " ; const router = Router (); const AUTH = " Basic " + Buffer . from ( ` ${ process . env . FP_TOKEN_ID } : ${ process . env . FP_SECRET } ` ). toString ( " base64 " ); router . post ( " /webinars/:id/stream " , async ( req , res ) => { const r = await fetch ( " https://api.fastpix.io/v1/live/streams " , { method : " POST " , headers : { " Content-Type " : " application/json " , Authorization : AUTH }, body : JSON . stringify ({ playbackSettings : { accessPolicy : " public " }, }), }); if ( ! r . ok ) return res . status ( 502 ). json ({ error : " stream create failed " }); const stream = await r . json (); // persist against your webinar row: // streamId, streamKey (SECRET!), playbackId await db . webinar . update ( req . params . id , { streamId : stream . str

2026-07-08 原文 →
AI 资讯

HTTP Server — Request Lifecycle

Request lifecycle: một HTTP request đi qua đâu, và vì sao "quên gọi next()" làm request treo cho tới khi socket timeout Một request tới một Express hay Fastify server không phải là "gọi handler rồi trả về response". Nó là một chuỗi các bước theo thứ tự cố định: parse HTTP, chạy qua middleware/hook, match route, gọi handler, serialize, gửi response, đóng. Nếu bất kỳ bước nào không chuyển tiếp — Express không gọi next() , Fastify hook không reply.send() hay không return — request treo cho tới khi client hoặc server timeout đóng socket. Đây là loại lỗi không ném exception, không xuất hiện trong error log, chỉ hiện ra qua p99 latency phình lên và số socket ở trạng thái ESTABLISHED tăng dần. Hiểu chính xác lifecycle này là điều kiện tiên quyết để debug những request "biến mất" và để đặt middleware đúng thứ tự. Cơ chế hoạt động Bước dưới cùng giống nhau ở cả hai framework: Node core http.Server nhận TCP connection, parse HTTP request line + headers, phát event request với hai object IncomingMessage (req) và ServerResponse (res). Điểm khác nhau là những gì framework làm giữa lúc nhận request và lúc response ra khỏi socket. Express dựng một chuỗi middleware qua Router . Mỗi lần app.use(fn) hay app.get(path, fn) được gọi, Express bọc fn vào một Layer với path regex (thông qua path-to-regexp ) rồi push vào một stack. Khi request đến, Router.handle duyệt stack tuần tự: với mỗi layer, nếu path match, gọi fn(req, res, next) . next() là closure trỏ vào layer kế tiếp; chỉ khi nó được gọi thì layer sau mới chạy. Error handler được nhận diện bằng arity — hàm 4 tham số (err, req, res, next) — và chỉ được duyệt tới khi next(err) được gọi: import express from ' express ' const app = express () app . use ( express . json ({ limit : ' 1mb ' })) // 1. parse body app . use (( req , _res , next ) => { // 2. request id req . id = crypto . randomUUID () next () }) app . use (( req , _res , next ) => { // 3. auth const token = req . headers . authorization if ( ! token ) return next ( new Erro

2026-07-08 原文 →