惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
腾讯CDC
M
MIT News - Artificial intelligence
Y
Y Combinator Blog
L
LangChain Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
IT之家
IT之家
A
About on SuperTechFans
H
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
A Deep Dive into endpoint-plus: A Next-Gen, AI-Native Req...
Zane · 2026-06-27 · via DEV Community

Zane

💡 GitHub Repository: github.com/zandko/endpoint-plus

🌟 If you find this project helpful or inspiring, please give us a Star! We are actively looking for feedback, issues, and PRs to co-create the future of this project.

endpoint-plus

📌 1. Introduction: Do We Really Need Another Request Library?

In modern frontend engineering, network requests are much more complex than simply fetching some JSON data. Around every API call, developers must wrestle with four persistent daily headaches:

  1. The "Human Converter" Interface Tax: When backend developers hand you nested JSON responses containing dozens or hundreds of fields, you either manually write TypeScript interfaces by hand, or constantly paste them into unstable online formatters. Whenever an API field changes, updating types turns into a maintenance nightmare.
  2. Fragmentation Across Runtimes: Standard browser code uses fetch or axios. But WeChat Mini-programs and uni-app require proprietary wrapper APIs (wx.request or uni.request). Meanwhile, SSR contexts (like Nuxt/Next) require server-compatible clients. You end up maintaining three separate copies of headers, interceptors, and error handlers.
  3. Concurrent 401 Silent Token Refresh: When an auth token expires and multiple parallel requests hit the backend simultaneously, how do you cleanly pause all requests, push them into an execution queue, send exactly one token refresh request, and replay the queue with the fresh credentials without causing deadlocks?
  4. AI Assistant Hallucinations: In the era of AI-driven coding, tools like Cursor and GitHub Copilot frequently make up parameters, suggest obsolete APIs, or generate buggy fetch functions, wasting your time on debug cycles.

To solve these exact challenges, we built and open-sourced endpoint-plus — a next-generation, cross-platform request client and developer tooling suite designed to free developers from manual typing, multi-platform runtime discrepancies, and repetitive API configurations.


🏗️ 2. Core Architecture: The Power of Decoupling

endpoint-plus avoids the monolithic overhead of traditional request clients by introducing a highly abstract physical Transport Layer alongside a pluggable middleware pipeline.

graph TD
    A[API Calls in Application Code] --> B[endpoint-plus Core Client]
    B --> C[Interceptors & Onion-Model Middleware]
    C --> D[Transport Layer Interface]

    D -- Web / Node SSR --> E[Fetch / Axios Transport]
    D -- Miniapp / uni-app --> F[Miniapp Transport]

    B <--> G[Vite DevTools Plugin]
    G -- TS Compiler AST Scan --> H[Scan Source Code]
    G -- Capture Real Response --> I[Schema Inference quicktype]
    I --> J[Write local endpoint-types.d.ts]

1. Swappable Physical Transports

By splitting request definition from the actual underlying network implementation, endpoint-plus provides 100% unified code semantics. You simply swap the transport adapter upon client creation:

  • Standard Fetch (lightweight, zero external dependencies, recommended for modern browsers and Node 22+):
  import { createInstance, createFetchTransport } from 'endpoint-plus';
  const api = createInstance({ transport: createFetchTransport() });

  • Mini Program & uni-app (handles platform-specific requests, file uploads, and downloads):
  import { createMiniappTransport } from 'endpoint-plus/miniapp';
  const api = createInstance({ transport: createMiniappTransport({ runtime: wx }) });

  • Axios Transport (perfect for projects that require upload progress monitoring or legacy configurations):
  import { createAxiosTransport } from 'endpoint-plus/transports/axios';
  const api = createInstance({ transport: createAxiosTransport() });

2. Onion-Model Middleware

In addition to traditional request/response interceptors, endpoint-plus introduces a Koa/Express-style Onion-Model Middleware system. This lets you wrap the entire execution lifespan using async functions:

api.registerRequestMiddleware(async (config, next) => {
  const start = Date.now();
  try {
    // 1. Outer Onion layer: Executed before request dispatch
    const response = await next(config);
    // 2. Inner Onion layer: Executed after response resolves
    console.log(`Request to ${config.url} took ${Date.now() - start}ms`);
    return response;
  } catch (error) {
    // 3. Centralized error catching and circuit-breaking
    console.error('Middleware caught exception:', error);
    throw error;
  }
});


🔮 3. TypeScript Type Gymnastics: Compile-Time Path Pattern Matching

This is the killer type-safety feature of endpoint-plus: You do not need to manually cast generic arguments on every request. TypeScript parses the URL string and infers the correct response type directly at compile-time.

For instance, once you declare your routes in a .d.ts file:

declare module 'endpoint-plus' {
  namespace YwEndpoint {
    interface Routes {
      'GET /users': { response: User[] };
      'GET /users/:userId': { response: User };
      'POST /users': { response: User };
    }
  }
}

Your editor instantly provides type-safety and autocompletion:

// 🌟 TypeScript 5.0+ const generic parameter pattern matching
const userList = await api.get('/users');
//    ^? User[] (Inferred from GET /users)

const user = await api.get('/users/123');
//    ^? User (Even with a concrete ID '123', the parser matches it against ':userId' to return User)

// ❌ Typos and invalid paths are caught instantly by the compiler!
const err = await api.get('/usrs'); // TS Compiler Error

🧠 How the Type Parser Works Under the Hood

We leverage recursive conditional types to strip URL queries, hash anchors, and domain prefixes, parsing the path into segments and pattern-matching them against parameter templates:

type EndpointRoutePathMatches<
  TRoutePath extends string,
  TUrl extends string,
> = EndpointPathSegmentsMatch<
  EndpointSplitPath<TRoutePath>,
  EndpointSplitPath<EndpointUrlPath<TUrl>>
>;

This ensures strict backend-to-frontend type alignment without requiring heavy code-generation steps during hot-reloads.


⚡ 4. Killer Feature: Vite DevTools & Quiet Code Generator

Writing interface types by hand is tedious. That's why we built endpoint-plus-devtools (a Vite plugin).

Just add it to your vite.config.ts:

import { endpointPlusDevtools } from 'endpoint-plus-devtools/vite';

export default defineConfig({
  plugins: [endpointPlusDevtools()],
});

1. How It Operates

  • AST Scanning: When the Vite dev server boots, the plugin parses your source tree (.ts, .tsx, .vue) in the background, identifying all api.get / api.post calls to build a visual endpoint map.
  • Live Response Capture: Open the in-browser DevTools overlay, select an endpoint, and test it. The overlay captures the real JSON response payload returned by your backend.
  • Schema Generation: Click "Save", and the Node-side quicktype-core engine runs schema analysis to write clean, type-safe ambient declarations into your project.

2. Vite HMR Watcher Bypass & Editor Integration

  • Solving the HMR Loop: Writing types inside src/ ordinarily triggers Vite's hot-reload, which reloads the page and destroys the active DevTools state. We resolved this by explicitly invoking Vite's watcher API (server.watcher.unwatch(typegenAbsFile)) to temporarily exclude the generated .d.ts file from HMR loops, ensuring silent, instantaneous type updates.
  • Launch Editor: Next to each endpoint in the DevTools UI is an "Open in Editor" button. Clicking it triggers the launch-editor Node utility, instantly opening your local VS Code/Cursor/WebStorm and focusing directly on the line of code where the API call was declared!

🌊 5. High-Performance SSE (Server-Sent Events) Buffering for AI Apps

With the explosion of LLMs (like ChatGPT and Claude), Server-Sent Events are standard for token streaming. However, rendering updates on every single token (which can fire 30–50 times per second) results in high CPU usage and severe UI lag.

endpoint-plus provides a native SSE extension with an integrated eventBuffer batching queue:

import { createSseExtension } from 'endpoint-plus/extensions/sse';

const apiWithSse = api.use(createSseExtension());

await apiWithSse.sse<string>('/api/chat/stream', {
  method: 'POST',
  data: { prompt: 'Explain Quantum Computing' },

  // 🌟 High-performance animation frame rendering batcher
  eventBuffer: {
    maxDelay: 16,               // Flush every 16ms (matches 60Hz display frame rate)
    maxSize: 50,                // Max queue size
    strategy: 'animation-frame', // Batching strategy
  },

  // Token events are automatically accumulated and flushed, keeping UI frame rates stable!
  onBatch: (events) => {
    const chunkText = events.map(e => e.data).join('');
    appendChatText(chunkText);
  },
});

Furthermore, SSE streams automatically reuse global client headers, interceptors, authentication context (auth-token), and telemetry configurations.


🔌 6. Pluggable Enterprise-Grade Middleware

We believe in keeping bundles small. Everything in endpoint-plus is modular, allowing you to opt-in to plugins on-demand:

Plugin Name Import Path Core Problem Solved
refresh-token endpoint-plus/plugins/refresh-token Concurrency-safe request buffering, silent token refresh, and request replay
request-gate endpoint-plus/plugins/request-gate Request-level debounce, throttle, and duplicate form submission rejection
request-cache endpoint-plus/plugins/request-cache GET/HEAD in-memory TTL caching and in-flight duplicate request merging
auth-token endpoint-plus/plugins/auth-token Asynchronous/Synchronous dynamic header authentication injection
retry endpoint-plus/plugins/retry Safe automatic retries using exponential backoffs for transient errors (e.g., 429, 503)
typegen endpoint-plus/plugins/typegen Lightweight development-mode TS type generator

Concurrency-Safe Silent Token Refresh Example:

import { createRefreshTokenPlugin } from 'endpoint-plus/plugins/refresh-token';

api.use(
  createRefreshTokenPlugin({
    refreshRequest: {
      method: 'POST',
      url: '/auth/refresh-token',
    },
    resolveAccessToken: (res) => res.newAccessToken,
    onRefresh: async (session) => {
      // Safely saves the new token. 
      // All other parallel requests are queued and automatically replayed.
      await saveSession(session);
    },
  })
);


🤖 7. AI-Native: Preloaded Skills for LLM Copilots

To make AI assistants write accurate code, endpoint-plus includes preloaded AI Skills inside the package folder.

Copy them to your local customizations directory:

# Create local customizations folder
mkdir -p .agents/skills
# Copy instructions from node_modules
cp -r node_modules/endpoint-plus/skills .agents/skills/endpoint-plus

Once copied, your AI assistant (e.g. Cursor or Antigravity) will instantly read these files and learn our API layouts, SSE buffering options, and middleware patterns. You can prompt Cursor:

"Write an endpoint configuration with silent token refresh, deduplication gating, and export a get method"

The AI will output 100% accurate, compile-safe configurations without any hallucinated methods or parameters!


🤝 8. Join Us & Co-Create the Future

endpoint-plus is published under the permissive MIT License and is already powering complex, high-traffic cross-platform apps in production.

We welcome community feedback, pull requests, and ideas! We are actively seeking contributors for:

  1. More Transports: Adapters for Taro, React Native, or specific serverless edge environments.
  2. DevTools Enhancements: Richer UI dashboards, response speed graphs, and cache hits statistics.
  3. New Middleware: Plugins for payload validation, request signature generation, or mock response adapters.

If you like the project, check out our repository and drop us a Star ⭐️!