Skip to content

GramIO API Reference / @gramio/composer/dist

@gramio/composer/dist

Classes

ClassDescription
Composer-
EventQueueConcurrent event queue with graceful shutdown support. Processes events in parallel (like an event loop), not sequentially.

Interfaces

InterfaceDescription
ComposerOptionsComposer constructor options
ContextCallbackMarker type for context-aware callbacks in macro options. The framework replaces this with the actual handler context type at the call site.
EventComposerEventComposer interface — Composer + .on() + per-event derive tracking + custom methods
EventComposerConstructor-
MacroHooksWhat a macro can return when activated
MiddlewareInfoRead-only projection of a middleware entry for inspect()/trace()
RouteBuilderRoute builder passed to the builder-callback overload of route()

Type Aliases

Type AliasDescription
CompatibleEventsGiven an event map and a Narrowing type, yields the union of event names whose context type contains all keys from Narrowing.
ComposedMiddlewareComposed middleware: next is optional (acts as terminal continuation)
ComposerLikeMinimal structural type for constraining this in custom composer methods.
ContextOfExtracts the current accumulated context type (TOut) from an EventComposer or Composer instance type.
DeriveFromOptionsCollects all derive types from macros that are activated in TOptions. The result is intersected into the handler's context type.
DeriveHandlerFunction that computes additional context properties
ErrorHandlerError handler receives an object with error, context, and resolved kind
EventContextOfExtracts the context type for a specific event from an EventComposer instance, combining global TOut (like ContextOf) and per-event TDerives[E].
HandlerOptionsBuilds the options parameter type for handler methods. Includes preHandler plus all registered macro option types with ContextCallback markers replaced by TBaseCtx.
LazyFactoryLazy middleware factory — called per invocation
MacroDefA macro definition: either a function accepting options, or a plain hooks object (boolean shorthand).
MacroDefinitionsRegistry of named macro definitions
MacroDeriveTypeExtract the derive (context enrichment) type from a macro
MacroOptionTypeExtract the options type a macro accepts (boolean for shorthand macros)
MaybeArraySingle value or array
MiddlewareMiddleware function: receives context and next
MiddlewareTypeWhich method created a middleware entry
Nextnext() continuation function
RouteHandlerRoute handler: single middleware, array, or Composer instance
ScopeScope level for middleware propagation
TraceHandlerTrace callback invoked on middleware enter; returns cleanup called on exit
WithCtxRecursively replaces all ContextCallback occurrences in T with (ctx: TCtx) => unknown.

Variables

noopNext

const noopNext: Next

Defined in: composer/index.d.ts:496

No-op next function: () => Promise.resolve()


skip

const skip: Middleware<any>

Defined in: composer/index.d.ts:498

Pass-through middleware: calls next() immediately


stop

const stop: Middleware<any>

Defined in: composer/index.d.ts:500

Terminal middleware: does NOT call next()

Functions

buildFromOptions()

buildFromOptions<TCtx>(macros, options, handler): Middleware<TCtx>

Defined in: composer/index.d.ts:493

Composes a handler with macro hooks and preHandlers from an options object.

Execution order:

  1. options.preHandler array (explicit guards — user controls order)
  2. Per-macro in options property order: a. macro.preHandler (guard middleware) b. macro.derive (context enrichment; void return = stop chain)
  3. Main handler

Type Parameters

Type Parameter
TCtx

Parameters

ParameterType
macrosRecord<string, MacroDef<any, any>>
optionsRecord<string, unknown>
handlerMiddleware<TCtx>

Returns

Middleware<TCtx>


compose()

compose<T>(middlewares): ComposedMiddleware<T>

Defined in: composer/index.d.ts:132

Compose an array of middleware functions into a single middleware. Koa-style onion model: each middleware receives (context, next).

Type Parameters

Type Parameter
T

Parameters

ParameterType
middlewaresMiddleware<T>[]

Returns

ComposedMiddleware<T>


createComposer()

createComposer<TBase, TEventMap, TMethods>(config): object

Defined in: composer/index.d.ts:473

Creates a configured Composer class with type-safe .on() event discrimination.

Type Parameters

Type ParameterDefault type
TBase extends object-
TEventMap extends Record<string, TBase>object
TMethods extends Record<string, (...args) => any>object

Parameters

ParameterType
config{ discriminator: (context) => string; methods?: TMethods & ThisType<EventComposer<TBase, TEventMap, TBase, TBase, { }, { }, TMethods, { }> & TMethods>; types?: TEventMap; }
config.discriminator(context) => string
config.methods?TMethods & ThisType<EventComposer<TBase, TEventMap, TBase, TBase, { }, { }, TMethods, { }> & TMethods>
config.types?TEventMap

Returns

NameTypeDefined in
compose()<T>(middlewares) => ComposedMiddleware<T>composer/index.d.ts:479
ComposerEventComposerConstructor<TBase, TEventMap, TMethods>composer/index.d.ts:478
EventQueuetypeof EventQueuecomposer/index.d.ts:480

defineComposerMethods()

defineComposerMethods<TMethods>(methods): TMethods

Defined in: composer/index.d.ts:454

Helper to define custom composer methods with full TypeScript inference.

TypeScript cannot infer generic method signatures when they're passed directly inside createComposer({ methods: { ... } }) because TMethods is buried inside the nested return type { Composer: EventComposerConstructor<..., TMethods> }.

This helper has return type TMethods directly — which lets TypeScript preserve generic method signatures. Pass the result (via typeof) as the 3rd type argument to createComposer:

Type Parameters

Type Parameter
TMethods extends Record<string, (...args) => any>

Parameters

ParameterType
methodsTMethods

Returns

TMethods

Example

ts
const methods = defineComposerMethods({
  // Pattern: `this: TThis` + `ContextOf<TThis>` — zero annotation at call site
  command<TThis>(
    this: TThis,
    name: string,
    handler: Middleware<MessageCtx & ContextOf<TThis>>,
  ): TThis {
    return (this as any).on("message", (ctx: any, next: any) => {
      if (ctx.text === `/${name}`) return handler(ctx, next);
      return next();
    }) as TThis;
  },
});

const { Composer } = createComposer<Base, EventMap, typeof methods>({
  discriminator: (ctx) => ctx.updateType,
  methods,
});

// No annotation needed — derives flow in automatically:
new Composer()
  .derive(() => ({ user: { id: 1 } }))
  .command("start", (ctx) => ctx.user.id); // ✅

eventTypes()

eventTypes<TEventMap>(): TEventMap

Defined in: composer/index.d.ts:469

Phantom type carrier for event map inference. Returns undefined at runtime — exists purely for type-level inference so that TEventMap can be inferred from the types config field.

Type Parameters

Type Parameter
TEventMap extends Record<string, any>

Returns

TEventMap

Example

ts
const { Composer } = createComposer({
  discriminator: (ctx: BaseCtx) => ctx.updateType,
  types: eventTypes<EventMap>(),
  methods: { hears(trigger) { return this.on("message", ...); } },
});