Skip to content

docs: TRPC Subscription zAsyncIterable refactoring after zod v4 migration #6952

Closed

Description

@luap2703

Area of Improvement

I noticed that the docs aren't up to date (or don't consider) using zod v4 and subscriptions. The zAsyncIterable would need to look smth like this as of the updated z.ZodType

import { isTrackedEnvelope, tracked, TrackedEnvelope } from "@trpc/server";
import { z } from "zod";

function isAsyncIterable<TValue, TReturn = unknown>(
    value: unknown,
): value is AsyncIterable<TValue, TReturn> {
    return (
        !!value && typeof value === "object" && Symbol.asyncIterator in value
    );
}
const trackedEnvelopeSchema =
    z.custom<TrackedEnvelope<unknown>>(isTrackedEnvelope);
/**
 * A Zod schema helper designed specifically for validating async iterables. This schema ensures that:
 * 1. The value being validated is an async iterable.
 * 2. Each item yielded by the async iterable conforms to a specified type.
 * 3. The return value of the async iterable, if any, also conforms to a specified type.
 */
export function zAsyncIterable<
    TYieldIn,
    TYieldOut,
    TReturnIn = void,
    TReturnOut = void,
    Tracked extends boolean = false,
>(opts: {
    /**
     * Validate the value yielded by the async generator
     */
    yield: z.ZodType<TYieldOut, TYieldIn>;
    /**
     * Validate the return value of the async generator
     * @remark not applicable for subscriptions
     */
    return?: z.ZodType<TReturnOut, TReturnIn>;
    /**
     * Whether if the yielded values are tracked
     * @remark only applicable for subscriptions
     */
    tracked?: Tracked;
}) {
    return z
        .custom<
            AsyncIterable<
                Tracked extends true ? TrackedEnvelope<TYieldIn> : TYieldIn,
                TReturnIn
            >
        >((val) => isAsyncIterable(val))
        .transform(async function* (iter) {
            const iterator = iter[Symbol.asyncIterator]();
            try {
                let next;
                while ((next = await iterator.next()) && !next.done) {
                    if (opts.tracked) {
                        const [id, data] = trackedEnvelopeSchema.parse(
                            next.value,
                        );
                        yield tracked(id, await opts.yield.parseAsync(data));
                        continue;
                    }
                    yield opts.yield.parseAsync(next.value);
                }
                if (opts.return) {
                    return await opts.return.parseAsync(next.value);
                }
                return;
            } finally {
                await iterator.return?.();
            }
        }) as z.ZodType<
        AsyncIterable<
            Tracked extends true ? TrackedEnvelope<TYieldIn> : TYieldIn,
            TReturnIn
        >,
        AsyncIterable<
            Tracked extends true ? TrackedEnvelope<TYieldOut> : TYieldOut,
            TReturnOut
        >
    >;
}

Link to related docs

No response

Additional information

No response

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR implementing the suggested changes!

Activity

  1. added
    📚 documentation / examples
    on Sep 20, 2025
  2. added
    ✅ accepted-PRs-welcome
    on Sep 21, 2025
  3. Wesley-Young commented on Oct 11, 2025

    @Wesley-Young

    This helped me a lot when I am upgrading my code👍

  4. chancegraff commented on Feb 12, 2026

    @chancegraff

    Full TypeScript compatible version without as casting (Tracked might not work fully in this version):

    import { isTrackedEnvelope, tracked, type TrackedEnvelope } from '@trpc/server';
    import { z } from 'zod';
    
    function isAsyncIterable<TValue, TReturn = unknown>(
      value: unknown
    ): value is AsyncIterable<TValue, TReturn> {
      return !!value && typeof value === 'object' && Symbol.asyncIterator in value;
    }
    
    /**
     * A Zod schema helper designed specifically for validating async iterables. This schema ensures that:
     * 1. The value being validated is an async iterable.
     * 2. Each item yielded by the async iterable conforms to a specified type.
     * 3. The return value of the async iterable, if any, also conforms to a specified type.
     */
    
    // Non-tracked overload
    export function ZodAsyncIterable<
      TYieldIn,
      TYieldOut,
      TReturnIn = void,
      TReturnOut = void,
    >(opts: {
      yield: z.ZodType<TYieldOut, TYieldIn>;
      return?: z.ZodType<TReturnOut, TReturnIn>;
      tracked?: false;
    }): z.ZodPipe<
      z.ZodCustom<AsyncIterable<TYieldIn, TReturnIn>, AsyncIterable<TYieldIn, TReturnIn>>,
      z.ZodTransform<
        AsyncGenerator<Awaited<TYieldOut>, Awaited<TReturnOut> | undefined, unknown>,
        AsyncIterable<TYieldIn, TReturnIn>
      >
    >;
    
    // Tracked overload
    export function ZodAsyncIterable<
      TYieldIn,
      TYieldOut,
      TReturnIn = void,
      TReturnOut = void,
    >(opts: {
      yield: z.ZodType<TYieldOut, TYieldIn>;
      return?: z.ZodType<TReturnOut, TReturnIn>;
      tracked: true;
    }): z.ZodPipe<
      z.ZodCustom<
        AsyncIterable<TrackedEnvelope<TYieldIn>, TReturnIn>,
        AsyncIterable<TrackedEnvelope<TYieldIn>, TReturnIn>
      >,
      z.ZodTransform<
        AsyncGenerator<TrackedEnvelope<Awaited<TYieldOut>>, Awaited<TReturnOut> | undefined, unknown>,
        AsyncIterable<TrackedEnvelope<TYieldIn>, TReturnIn>
      >
    >;
    
    // Implementation
    export function ZodAsyncIterable<
      TYieldIn,
      TYieldOut,
      TReturnIn = void,
      TReturnOut = void,
    >(opts: {
      /**
       * Validate the value yielded by the async generator
       */
      yield: z.ZodType<TYieldOut, TYieldIn>;
      /**
       * Validate the return value of the async generator
       * @remark not applicable for subscriptions
       */
      return?: z.ZodType<TReturnOut, TReturnIn>;
      /**
       * Whether if the yielded values are tracked
       * @remark only applicable for subscriptions
       */
      tracked?: boolean;
    }) {
      return z
        .custom<AsyncIterable<TYieldIn | TrackedEnvelope<TYieldIn>, TReturnIn>>(
          (val) => isAsyncIterable(val)
        )
        .transform(async function* (iter) {
          const iterator = iter[Symbol.asyncIterator]();
          try {
            let next;
            while ((next = await iterator.next()) && !next.done) {
              if (opts.tracked) {
                const [id, data] = z
                  .custom<TrackedEnvelope<unknown>>(isTrackedEnvelope)
                  .parse(next.value);
                yield tracked(id, await opts.yield.parseAsync(data));
                continue;
              }
              yield opts.yield.parseAsync(next.value);
            }
            if (opts.return) {
              return await opts.return.parseAsync(next.value);
            }
            return;
          } finally {
            await iterator.return?.();
          }
        });
    }
  5. cogwirrel commented on Feb 19, 2026

    @cogwirrel
    Contributor

    Thanks for this! Do you think there'd be scope to export this helper as part of tRPC? Would be handy not to have to copy/paste :)

  6. added a commit that references this issue on Feb 28, 2026
    41723ce
  7. github-actions commented on Mar 1, 2026

    @github-actions
    Contributor

    This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.

  8. locked as resolved and limited conversation to collaborators on Mar 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✅ accepted-PRs-welcome📚 documentation / examples

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions