@gramio/composer

中文文档
0.5.0发布于 2026/06/04MITTypeScriptESM + CJS零依赖近 30 天下载 5686

用于 TypeScript 的通用、 类型安全中件组件库

中文使用文档
文档目录12 节
  1. 特征
  2. 安装
  3. 快速启动
  4. API 密码
  5. compose(middlewares)
  6. Composer
  7. 范围系统
  8. 插件复制
  9. createComposer(config) - 事件系统
  10. EventQueue
  11. 宏系统
  12. 公用事业

@ gramio/ composer (英语)

npm npm downloads JSR JSR Score

用于TypeScript的通用,型号安全的中件组成库. 零从属. 交叉运行时间(Bun / Node.js / Deno).

特征

  • 科亚式洋葱中件组成
  • 类型安全上下文累积 derive()
  • 范围隔离(局部/范围/全球),如Elysia
  • 插件由名称 + 种子复制
  • 通过工厂模式的抽象事件系统(.on()(中文(简体) )
  • 以优雅的关闭同步事件队列
  • 分枝、出行、叉子、懒惰的中间软件

安装

# npm
npm install @gramio/composer

# bun
bun add @gramio/composer

# deno
deno add jsr:@gramio/composer

快速启动

import { Composer } from "@gramio/composer";

const app = new Composer<{ request: Request }>()
  .use(async (ctx, next) => {
    console.log("before");
    await next();
    console.log("after");
  })
  .derive((ctx) => ({
    url: new URL(ctx.request.url),
  }))
  .use((ctx, next) => {
    console.log(ctx.url.pathname); // typed!
    return next();
  });

await app.run({ request: new Request("https://example.com/hello") });

API 密码

compose(middlewares)

独立的可口型洋葱成分. 取出一系列中间软件,返回一个由单一构成的中间软件.

import { compose } from "@gramio/composer";

const handler = compose([
  async (ctx, next) => { console.log(1); await next(); console.log(4); },
  async (ctx, next) => { console.log(2); await next(); console.log(3); },
]);

await handler({});
// 1 → 2 → 3 → 4

Composer

核心类. 登记具有类型安全上下文累积的中间软件.

use(...middleware)

注册原始中间软件功能 .

app.use((ctx, next) => {
  // do something
  return next();
});

derive(handler, options?)

计算和指定额外的上下文属性。 之后的中间软件可以看到新的类型.

app
  .derive((ctx) => ({ user: getUser(ctx) }))
  .use((ctx, next) => {
    ctx.user; // typed!
    return next();
  });

范围传播:

const plugin = new Composer({ name: "auth" })
  .derive((ctx) => ({ user: getUser(ctx) }), { as: "scoped" });

guard(predicate, ...middleware)

取决于是否提供处理器的两个模式:

与处理器 ——在真实状态下将中间软件作为副作用运行,始终延续链:

app.guard(
  (ctx): ctx is WithText => "text" in ctx,
  (ctx, next) => { /* ctx.text is typed */ return next(); }
);

没有处理器( 门模式) ——如果是假的,就停止这个作曲家所留下的中件. 当使用类型上游时,下游上下文会缩小:

// Only admin can reach subsequent middleware
app
  .guard((ctx) => ctx.role === "admin")
  .use(adminOnlyHandler);  // skipped if not admin

// Type predicate narrows context for all downstream handlers
app
  .guard((ctx): ctx is Ctx & { text: string } => "text" in ctx)
  .on("message", (ctx, next) => {
    ctx.text; // string (narrowed by guard)
    return next();
  });

当在内部使用时 extend()- 被插件, 守护者停止了插件的链条, 但父程序继续 :

const adminPlugin = new Composer()
  .guard((ctx) => ctx.isAdmin)
  .use(adminDashboard);          // skipped if not admin

app
  .extend(adminPlugin)  // guard inside, isolated
  .use(alwaysRuns);     // parent continues regardless

branch(predicate, onTrue, onFalse?)

如果/结束分支。 注册时静态布尔优化 .

app.branch(
  (ctx) => ctx.isAdmin,
  adminHandler,
  userHandler
);

route(router, cases, fallback?)

多向调度(如开关).

app.route(
  (ctx) => ctx.type,
  {
    message: handleMessage,
    callback: handleCallback,
  },
  handleFallback
);

fork(...middleware)

火与忘相并处. 不阻断主链.

app.fork(analyticsMiddleware);

tap(...middleware)

运行中间软件但总是继续链(无法停止).

app.tap(loggingMiddleware);

lazy(factory)

动态中间软件选择 。 工厂被调用到每一个引用(而不是缓存).

app.lazy((ctx) => ctx.premium ? premiumHandler : freeHandler);

onError(handler)

之后所有中间软件的错误边界 .

app.onError((ctx, error) => {
  console.error(error);
});

group(fn)

被隔离的子链. 组内衍生物不会泄露给父母.

app.group((g) => {
  g.derive(() => ({ internal: true }))
   .use((ctx, next) => {
     ctx.internal; // available here
     return next();
   });
});
// ctx.internal is NOT available here

extend(other)

合并另一位作曲家. 范围认识与去德普.

const auth = new Composer({ name: "auth" })
  .derive(() => ({ user: "alice" }))
  .as("scoped");

app.extend(auth);
// app now sees ctx.user

as(scope)

推动所有中间软件 "scoped" (一级)或 "global" (各级).

compose() 编号 : run(context)

编译到单个中件或直接运行.

const handler = app.compose();
await handler(ctx);

// or
await app.run(ctx);

范围系统

何时 parent.extend(child)数字 :

儿童范围对父母的影响
local (默认)隔绝通过 Object.create() - 食物不会漏出
scoped合并为父, 停在那里( 一级)
global合并为父母并传播给所有祖先

插件复制

具有一个 name 被贬低。 同名+种子 = 在第二次扩展时跳出.

const auth = new Composer({ name: "auth" });
app.extend(auth); // applied
app.extend(auth); // skipped

不同的种子 = 不同的插件 :

const limit100 = new Composer({ name: "rate-limit", seed: { max: 100 } });
const limit200 = new Composer({ name: "rate-limit", seed: { max: 200 } });
app.extend(limit100); // applied
app.extend(limit200); // applied (different seed)

[尖叫声] Dedup在注册时间去除中间软件——而不是在每次请求的运行时间.

如果共享插件( 例如 ). withUser) 只在子集成器内扩展,其 derive 运行在每个子集成器的隔离组内. 当解除时 来源于第二分集器, ctx.user 第一组设置为: 没有 可见 中——类型Script类型正确,运行时间值为 undefined。 。 。 .

修补 : 将共享的作曲者扩展至必须提供其数据的级别, 并让分集器只为类型安全(dedup防止双重执行)而扩展.

// ✅ correct — withUser runs once on the real ctx, both routers see ctx.user
app
  .extend(withUser)    // derive on real ctx
  .extend(adminRouter) // withUser inside → deduped (skipped)
  .extend(chatRouter); // withUser inside → deduped (skipped)

// ⚠️  risky — works only if routers are mutually exclusive (one handles per update)
app
  .extend(adminRouter) // withUser runs in isolation group
  .extend(chatRouter); // withUser deduped → chatHandlers can't see ctx.user

见 docs/layered-composers.md 完全崩溃.

createComposer(config) - 事件系统

制造混音器的工厂 .on() 歧视事件.

import { createComposer } from "@gramio/composer";

interface BaseCtx { updateType: string }
interface MessageCtx extends BaseCtx { text?: string }
interface CallbackCtx extends BaseCtx { data?: string }

const { Composer, EventQueue } = createComposer<BaseCtx, {
  message: MessageCtx;
  callback_query: CallbackCtx;
}>({
  discriminator: (ctx) => ctx.updateType,
});

const app = new Composer()
  .derive(() => ({ timestamp: Date.now() }))
  .on("message", (ctx, next) => {
    ctx.text;      // string | undefined
    ctx.timestamp;  // number
    return next();
  })
  .on("callback_query", (ctx, next) => {
    ctx.data;       // string | undefined
    return next();
  });

.on() 有过滤器

仅过滤( 无事件名称) - 双弧 on(filter, handler) 将过滤器应用到 全部 按事件类型分列的没有歧视的事件:

// Type-narrowing filter — handler sees narrowed context across all compatible events
app.on(
  (ctx): ctx is { text: string } => typeof (ctx as any).text === "string",
  (ctx, next) => {
    ctx.text; // string (narrowed)
    return next();
  },
);

// Boolean filter — no narrowing, handler gets base TOut
app.on(
  (ctx) => ctx.updateType === "message",
  (ctx, next) => {
    // no type narrowing, full context
    return next();
  },
);

事件+过滤器 - 3号线 on(event, filter, handler) 支持缩小类型上游和布尔过滤器:

// Type-narrowing filter — handler sees narrowed context
app.on(
  "message",
  (ctx): ctx is MessageCtx & { text: string } => ctx.text !== undefined,
  (ctx, next) => {
    ctx.text; // string (narrowed, not string | undefined)
    return next();
  },
);

// Boolean filter — no narrowing, handler sees full context
app.on(
  "message",
  (ctx) => ctx.text !== undefined,
  (ctx, next) => {
    ctx.text; // string | undefined (not narrowed)
    return next();
  },
);

二号线 on() 也接受可选 Patch 用于上下文扩展名( 自定义方法有用) :

app.on<"message", { args: string }>("message", (ctx, next) => {
  ctx.args; // string — type-safe without casting
  return next();
});

.use() 支持同样的 Patch 通用——当自定义方法丰富上下文后,再授权给用户提供的处理器时方便:

app.use<{ args: string }>((ctx, next) => {
  ctx.args; // string — type-safe without casting
  return next();
});

Patch 不变 TOut ——是一个处理器的局部逃生舱,而不是永久性上下文扩展. 使用 derive() 当你希望添加的 传播到所有下游中间软件.

types + 键 eventTypes() ——奇幻类推

TypeScript 无法部分推断类型参数, 所以当您同时需要时 TEventMap 财务报告和审定财务报表 TMethods 一起推断,使用 types 幽灵地与 eventTypes() 帮助而不是显性类型参数 :

import { createComposer, eventTypes } from "@gramio/composer";

// eventTypes<T>() returns undefined at runtime — purely for inference
const { Composer } = createComposer({
  discriminator: (ctx: BaseCtx) => ctx.updateType,
  types: eventTypes<{ message: MessageCtx; callback_query: CallbackCtx }>(),
});
// TBase inferred from discriminator, TEventMap inferred from types

methods ——自定义原型方法

直接将特定框架 DX 糖注入作曲器原型. 自定义方法通过 全部 方法链on, (中文(简体) ), use, (中文(简体) ), derive, (中文(简体) ), extend(见A/C.5/49/70,附件)。 如果一个方法名称与内置名称相撞, 运行时间冲突检查会丢出 .

简单方法 直接从事下列工作: methods数字 :

const { Composer } = createComposer({
  discriminator: (ctx: BaseCtx) => ctx.updateType,
  types: eventTypes<{ message: MessageCtx }>(),
  methods: {
    hears(trigger: RegExp | string, handler: (ctx: MessageCtx) => unknown) {
      return this.on("message", (ctx, next) => {
        const text = ctx.text;
        if (
          (typeof trigger === "string" && text === trigger) ||
          (trigger instanceof RegExp && text && trigger.test(text))
        ) {
          return handler(ctx);
        }
        return next();
      });
    },
  },
});

累积所得方法 需要两个步骤。 TypeScript 无法在 TMethods 嵌入返回类型 createComposer,因此使用 defineComposerMethods 首先,它的返回类型是直接的 TMethods,保留了通用签名。 那就通过 typeof methods 作为第3种论证.

使用 ComposerLike<TThis> 作为F项限制,以便 this.on(...) 已全部输入并返回 TThis - 不需要铸花板.

模式 : this: TThis + 键 ContextOf<TThis> ——呼叫站点零注释:

import { createComposer, defineComposerMethods, eventTypes } from "@gramio/composer";
import type { ComposerLike, ContextOf, Middleware } from "@gramio/composer";

const methods = defineComposerMethods({
  command<TThis extends ComposerLike<TThis>>(
    this: TThis,
    name: string,
    handler: Middleware<MessageCtx & ContextOf<TThis>>,
  ): TThis {
    const inner: Middleware<MessageCtx & ContextOf<TThis>> = (ctx, next) => {
      if (ctx.text === `/${name}`) return handler(ctx, next);
      return next();
    };
    return this.on("message", inner);
  },
});

const { Composer } = createComposer<BaseCtx, { message: MessageCtx }, typeof methods>({
  discriminator: (ctx) => ctx.updateType,
  methods,
});

// Derives flow into the handler automatically — no annotation needed:
new Composer()
  .derive(() => ({ user: { id: 1, name: "Alice" } }))
  .command("start", (ctx, next) => {
    ctx.user.id;   // ✅ typed — inferred from ContextOf<TThis>
    ctx.text;      // ✅ string | undefined — from MessageCtx
    return next();
  });

ContextOf<T> — 提取当前上下文类型

摘录 TOut (毕竟是完全累积的上下文类型) .derive() 财务报告和审定财务报表 .decorate() 调用)来自作曲家或事件composer实例类型.

命名插件的回用上下文类型 :

import type { ContextOf } from "@gramio/composer";

const withUser = new Composer()
  .derive(async (ctx) => ({
    user: await db.getUser(ctx.userId),
  }));

// Extract the enriched context — no manual conditional type needed
export type WithUser = ContextOf<typeof withUser>;
// WithUser = { userId: string } & { user: User }

// Use it in standalone functions, other plugins, or type assertions:
function requireAdmin(ctx: WithUser) {
  if (!ctx.user.isAdmin) throw new Error("Forbidden");
}

在自定义方法签名中 —— 说 ContextOf<TThis> 捕捉所有在呼叫站点累积的出自:

command<TThis extends ComposerLike<TThis>>(
  this: TThis,
  handler: Middleware<ContextOf<TThis>>,
): TThis

EventContextOf<T, E> - 摘取特定活动的背景(全球+每个活动来源)

喜欢 ContextOf<T>,但也包括通过 derive(event, handler)。 。 。 .

包括
ContextOf<TThis>TOut ——只有全球来源
EventContextOf<TThis, "message">TOut & TDerives["message"] ——全球 财务报告和审定财务报表 每起事件

为什么这很重要: 当自定义方法总是向特定事件(如:. command → "message"),它的处理者也应该看到事件的源出. 与 ContextOf 一个人,a derive("message", ...) 插件的类型在处理器内部是看不见的,即使值在运行时存在.

import { createComposer, defineComposerMethods, eventTypes } from "@gramio/composer";
import type { ComposerLike, EventContextOf, Middleware } from "@gramio/composer";

const methods = defineComposerMethods({
  command<TThis extends ComposerLike<TThis>>(
    this: TThis,
    name: string,
    //                  ↓ EventContextOf instead of ContextOf
    handler: Middleware<MessageCtx & EventContextOf<TThis, "message">>,
  ): TThis {
    return this.on("message", (ctx: any, next: Next) => {
      if (ctx.text === `/${name}`) return handler(ctx, next);
      return next();
    });
  },
});

const { Composer } = createComposer<BaseCtx, { message: MessageCtx }, typeof methods>({
  discriminator: (ctx) => ctx.updateType,
  methods,
});

// Per-event plugin that adds `t` only for message events:
const i18nPlugin = new Composer({ name: "i18n" })
  .derive("message", (ctx) => ({
    t: i18n.buildT(ctx.from?.languageCode ?? "en"),
  }))
  .as("scoped");

new Composer()
  .extend(i18nPlugin)
  .command("start", (ctx, next) => {
    ctx.t("Hello");   // ✅ typed — EventContextOf sees TDerives["message"]
    ctx.text;         // ✅ string | undefined — from MessageCtx
    return next();
  })
  .on("message", (ctx, next) => {
    ctx.t("Hi");      // ✅ also works here via ResolveEventCtx
    return next();
  });

[注] 如果该衍生物在全球注册(.derive(() => ...) 既无事件名称,又无事件名称 ContextOf 财务报告和审定财务报表 EventContextOf 将看到它。 活动来源derive("message", ...)) 仅通过 EventContextOf 在自定义方法签名中,或直接在内部 .on("message", ...) 管理者.

ComposerLike<T> 最低结构类型 this 约束

最小接口 { on(event: any, handler: any): T } 用作对 TThis创建 this.on(...) 已全部输入并返回 TThis 没有铸造物.

import type { ComposerLike } from "@gramio/composer";

// Constraint in a custom method:
command<TThis extends ComposerLike<TThis>>(this: TThis, ...): TThis {
  return this.on("message", inner); // returns TThis — no `as TThis` needed
}

EventQueue

同步事件队列以优雅的关闭 .

import { EventQueue } from "@gramio/composer";

const queue = new EventQueue<RawEvent>(async (event) => {
  const ctx = createContext(event);
  return app.run(ctx);
});

queue.add(event);
queue.addBatch(events);

// Graceful shutdown (waits up to 5s for pending handlers)
await queue.stop(5000);

宏系统

由 : 爱丽西亚宏。将可重复使用的行为(监护、率限制、认证)登记为宏,然后通过处理器方法上的选项对象激活.

macro(name, definition) 编号 : macro(definitions)

在作曲家或事件composer实例上注册宏.

import { Composer, type MacroDef, type ContextCallback } from "@gramio/composer";

// Boolean shorthand macro — plain hooks object
const onlyAdmin: MacroDef<void, {}> = {
  preHandler: (ctx, next) => {
    if (ctx.role !== "admin") return; // stops chain
    return next();
  },
};

// Parameterized macro — function receiving options
interface ThrottleOptions {
  limit: number;
  window?: number;
  onLimit?: ContextCallback; // ← replaced with actual ctx type at call site
}

const throttle: MacroDef<ThrottleOptions, {}> = (opts) => ({
  preHandler: createThrottleMiddleware(opts),
});

// Macro with derive — enriches handler context
interface AuthDerived { user: { id: number; name: string } }

const auth: MacroDef<void, AuthDerived> = {
  derive: async (ctx) => {
    const user = await getUser(ctx.token);
    if (!user) return; // void = stop chain (guard behavior)
    return { user };
  },
};

const app = new Composer()
  .macro("onlyAdmin", onlyAdmin)
  .macro({ throttle, auth }); // batch registration

buildFromOptions(macros, options, handler)

由宏钩子构成的处理器的运行时助手. 内部被框架用来将宏接入处理器方法.

import { buildFromOptions } from "@gramio/composer";

// Execution order:
// 1. options.preHandler[] (explicit guards — user controls order)
// 2. Per-macro in options property order:
//    a. macro.preHandler (guard middleware)
//    b. macro.derive (context enrichment; void = stop chain)
// 3. Main handler
const composed = buildFromOptions(
  app["~"].macros,
  { auth: true, throttle: { limit: 5 } },
  mainHandler,
);

宏类型

import type {
  MacroDef,          // Macro definition (function or hooks object)
  MacroHooks,        // { preHandler?, derive? }
  MacroDefinitions,  // Record<string, MacroDef<any, any>>
  ContextCallback,   // Marker type for context-aware callbacks
  WithCtx,           // Recursively replaces ContextCallback with real ctx type
  HandlerOptions,    // Builds the options parameter type for handler methods
  DeriveFromOptions, // Collects derive types from activated macros
  MacroOptionType,   // Extracts option type from MacroDef
  MacroDeriveType,   // Extracts derive return type from MacroDef
} from "@gramio/composer";

公用事业

import { noopNext, skip, stop } from "@gramio/composer";

noopNext;  // () => Promise.resolve()
skip;      // middleware that calls next()
stop;      // middleware that does NOT call next()

版本与发布记录

@gramio/composer 共发布 10 个版本,首次发布于 2026/02/17;过去 12 个月发布了 10 个版本。

版本发布日期距今
0.5.0latest2026/06/045 个月前
0.4.12026/03/207 个月前
0.4.02026/03/207 个月前
0.3.42026/03/038 个月前
0.3.32026/02/288 个月前
0.3.12026/02/278 个月前

关于 @gramio/composer 的常见问题

@gramio/composer 是什么?

用于 TypeScript 的通用、 类型安全中件组件库

如何安装 @gramio/composer?

在项目目录运行 npm install @gramio/composer,或使用 pnpm add / yarn add / bun add。

@gramio/composer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gramio/composer 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gramio/composer 可以商用吗?

@gramio/composer 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gramio/composer 的下载量有多少?

根据 npm 官方下载统计,@gramio/composer 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,686 次,日均约 190 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gramio/composer 还在维护吗?

最新版本 0.5.0 发布于 2026/06/04(5 个月前);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/02/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。