{"version":3,"file":"tracked-D4jU_Hb3.mjs","names":[],"sources":["../src/unstable-core-do-not-import/error/formatter.ts","../src/unstable-core-do-not-import/error/TRPCError.ts","../src/unstable-core-do-not-import/transformer.ts","../src/unstable-core-do-not-import/router.ts","../src/unstable-core-do-not-import/stream/tracked.ts"],"sourcesContent":["import type { ProcedureType } from '../procedure';\nimport type {\n  TRPC_ERROR_CODE_KEY,\n  TRPC_ERROR_CODE_NUMBER,\n  TRPCErrorShape,\n} from '../rpc';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (opts: {\n  error: TRPCError;\n  type: ProcedureType | 'unknown';\n  path: string | undefined;\n  input: unknown;\n  ctx: TContext | undefined;\n  shape: DefaultErrorShape;\n}) => TShape;\n\n/**\n * @internal\n */\nexport type DefaultErrorData = {\n  code: TRPC_ERROR_CODE_KEY;\n  httpStatus: number;\n  /**\n   * Path to the procedure that threw the error\n   */\n  path?: string;\n  /**\n   * Stack trace of the error (only in development)\n   */\n  stack?: string;\n};\n\n/**\n * @internal\n */\nexport interface DefaultErrorShape extends TRPCErrorShape<DefaultErrorData> {\n  message: string;\n  code: TRPC_ERROR_CODE_NUMBER;\n}\n\nexport const defaultFormatter: ErrorFormatter<any, any> = ({ shape }) => {\n  return shape;\n};\n","import type { TRPC_ERROR_CODE_KEY } from '../rpc/codes';\nimport { isObject } from '../utils';\n\nclass UnknownCauseError extends Error {\n  [key: string]: unknown;\n\n  constructor(cause: object) {\n    super(getMessage(cause));\n    Object.assign(this, cause);\n  }\n}\n\nfunction getMessage(cause: object) {\n  if ('message' in cause) return String(cause.message);\n\n  return undefined;\n}\n\nexport function getCauseFromUnknown(cause: unknown): Error | undefined {\n  if (cause instanceof Error) {\n    return cause;\n  }\n\n  const type = typeof cause;\n  if (type === 'undefined' || type === 'function' || cause === null) {\n    return undefined;\n  }\n\n  // Primitive types just get wrapped in an error\n  if (type !== 'object') {\n    // eslint-disable-next-line @typescript-eslint/no-base-to-string\n    return new Error(String(cause));\n  }\n\n  // If it's an object, we'll create a synthetic error\n  if (isObject(cause)) {\n    return new UnknownCauseError(cause);\n  }\n\n  return undefined;\n}\n\nexport function getTRPCErrorFromUnknown(cause: unknown): TRPCError {\n  if (cause instanceof TRPCError) {\n    return cause;\n  }\n  if (cause instanceof Error && cause.name === 'TRPCError') {\n    // https://github.com/trpc/trpc/pull/4848\n    return cause as TRPCError;\n  }\n\n  const trpcError = new TRPCError({\n    code: 'INTERNAL_SERVER_ERROR',\n    cause,\n  });\n\n  // Inherit stack from error\n  if (cause instanceof Error && cause.stack) {\n    trpcError.stack = cause.stack;\n  }\n\n  return trpcError;\n}\n\nexport class TRPCError extends Error {\n  // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n  // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n  public override readonly cause?: Error;\n  public readonly code;\n\n  constructor(opts: {\n    message?: string;\n    code: TRPC_ERROR_CODE_KEY;\n    cause?: unknown;\n  }) {\n    const cause = getCauseFromUnknown(opts.cause);\n    const message = opts.message ?? cause?.message ?? opts.code;\n\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore https://github.com/tc39/proposal-error-cause\n    super(message, { cause });\n\n    this.code = opts.code;\n    this.name = 'TRPCError';\n    this.cause ??= cause;\n  }\n}\n","import type { AnyRootTypes, RootConfig } from './rootConfig';\nimport type { AnyRouter, inferRouterError } from './router';\nimport type {\n  TRPCResponse,\n  TRPCResponseMessage,\n  TRPCResultMessage,\n} from './rpc';\nimport { isObject } from './utils';\n\n/**\n * @public\n */\nexport interface DataTransformer {\n  serialize(object: any): any;\n  deserialize(object: any): any;\n}\n\ninterface InputDataTransformer extends DataTransformer {\n  /**\n   * This function runs **on the client** before sending the data to the server.\n   */\n  serialize(object: any): any;\n  /**\n   * This function runs **on the server** to transform the data before it is passed to the resolver\n   */\n  deserialize(object: any): any;\n}\n\ninterface OutputDataTransformer extends DataTransformer {\n  /**\n   * This function runs **on the server** before sending the data to the client.\n   */\n  serialize(object: any): any;\n  /**\n   * This function runs **only on the client** to transform the data sent from the server.\n   */\n  deserialize(object: any): any;\n}\n\n/**\n * @public\n */\nexport interface CombinedDataTransformer {\n  /**\n   * Specify how the data sent from the client to the server should be transformed.\n   */\n  input: InputDataTransformer;\n  /**\n   * Specify how the data sent from the server to the client should be transformed.\n   */\n  output: OutputDataTransformer;\n}\n\n/**\n * @public\n */\nexport type CombinedDataTransformerClient = {\n  input: Pick<CombinedDataTransformer['input'], 'serialize'>;\n  output: Pick<CombinedDataTransformer['output'], 'deserialize'>;\n};\n\n/**\n * @public\n */\nexport type DataTransformerOptions = CombinedDataTransformer | DataTransformer;\n\n/**\n * @internal\n */\nexport function getDataTransformer(\n  transformer: DataTransformerOptions,\n): CombinedDataTransformer {\n  if ('input' in transformer) {\n    return transformer;\n  }\n  return { input: transformer, output: transformer };\n}\n\n/**\n * @internal\n */\nexport const defaultTransformer: CombinedDataTransformer = {\n  input: { serialize: (obj) => obj, deserialize: (obj) => obj },\n  output: { serialize: (obj) => obj, deserialize: (obj) => obj },\n};\n\nfunction transformTRPCResponseItem<\n  TResponseItem extends TRPCResponse | TRPCResponseMessage,\n>(config: RootConfig<AnyRootTypes>, item: TResponseItem): TResponseItem {\n  if ('error' in item) {\n    return {\n      ...item,\n      error: config.transformer.output.serialize(item.error),\n    };\n  }\n\n  if ('data' in item.result) {\n    return {\n      ...item,\n      result: {\n        ...item.result,\n        data: config.transformer.output.serialize(item.result.data),\n      },\n    };\n  }\n\n  return item;\n}\n\n/**\n * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers\n **/\nexport function transformTRPCResponse<\n  TResponse extends\n    TRPCResponse | TRPCResponse[] | TRPCResponseMessage | TRPCResponseMessage[],\n>(config: RootConfig<AnyRootTypes>, itemOrItems: TResponse) {\n  return Array.isArray(itemOrItems)\n    ? itemOrItems.map((item) => transformTRPCResponseItem(config, item))\n    : transformTRPCResponseItem(config, itemOrItems);\n}\n\n// FIXME:\n// - the generics here are probably unnecessary\n// - the RPC-spec could probably be simplified to combine HTTP + WS\n/** @internal */\nfunction transformResultInner<TRouter extends AnyRouter, TOutput>(\n  response:\n    | TRPCResponse<TOutput, inferRouterError<TRouter>>\n    | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n  transformer: DataTransformer,\n) {\n  if ('error' in response) {\n    const error = transformer.deserialize(\n      response.error,\n    ) as inferRouterError<TRouter>;\n    return {\n      ok: false,\n      error: {\n        ...response,\n        error,\n      },\n    } as const;\n  }\n\n  const result = {\n    ...response.result,\n    ...((!response.result.type || response.result.type === 'data') && {\n      type: 'data',\n      data: transformer.deserialize(response.result.data),\n    }),\n  } as TRPCResultMessage<TOutput>['result'];\n  return { ok: true, result } as const;\n}\n\nclass TransformResultError extends Error {\n  constructor() {\n    super('Unable to transform response from server');\n  }\n}\n\n/**\n * Transforms and validates that the result is a valid TRPCResponse\n * @internal\n */\nexport function transformResult<TRouter extends AnyRouter, TOutput>(\n  response:\n    | TRPCResponse<TOutput, inferRouterError<TRouter>>\n    | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n  transformer: DataTransformer,\n): ReturnType<typeof transformResultInner> {\n  let result: ReturnType<typeof transformResultInner>;\n  try {\n    // Use the data transformers on the JSON-response\n    result = transformResultInner(response, transformer);\n  } catch {\n    throw new TransformResultError();\n  }\n\n  // check that output of the transformers is a valid TRPCResponse\n  if (\n    !result.ok &&\n    (!isObject(result.error.error) ||\n      typeof result.error.error['code'] !== 'number')\n  ) {\n    throw new TransformResultError();\n  }\n  if (result.ok && !isObject(result.result)) {\n    throw new TransformResultError();\n  }\n  return result;\n}\n","import type { Observable } from '../observable';\nimport { createRecursiveProxy } from './createProxy';\nimport { defaultFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n  AnyProcedure,\n  ErrorHandlerOptions,\n  inferProcedureInput,\n  inferProcedureOutput,\n  LegacyObservableSubscriptionProcedure,\n} from './procedure';\nimport type { ProcedureCallOptions } from './procedureBuilder';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { defaultTransformer } from './transformer';\nimport type { MaybePromise, ValueOf } from './types';\nimport {\n  emptyObject,\n  isFunction,\n  isObject,\n  mergeWithoutOverrides,\n} from './utils';\n\nexport interface RouterRecord {\n  [key: string]: AnyProcedure | RouterRecord;\n}\n\ntype DecorateProcedure<TProcedure extends AnyProcedure> = (\n  input: inferProcedureInput<TProcedure>,\n) => Promise<\n  TProcedure['_def']['type'] extends 'subscription'\n    ? TProcedure extends LegacyObservableSubscriptionProcedure<any>\n      ? Observable<inferProcedureOutput<TProcedure>, TRPCError>\n      : inferProcedureOutput<TProcedure>\n    : inferProcedureOutput<TProcedure>\n>;\n\n/**\n * @internal\n */\nexport type DecorateRouterRecord<TRecord extends RouterRecord> = {\n  [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n    ? $Value extends AnyProcedure\n      ? DecorateProcedure<$Value>\n      : $Value extends RouterRecord\n        ? DecorateRouterRecord<$Value>\n        : never\n    : never;\n};\n\n/**\n * @internal\n */\n\nexport type RouterCallerErrorHandler<TContext> = (\n  opts: ErrorHandlerOptions<TContext>,\n) => void;\n\n/**\n * @internal\n */\nexport type RouterCaller<\n  TRoot extends AnyRootTypes,\n  TRecord extends RouterRecord,\n> = (\n  /**\n   * @note\n   * If passing a function, we recommend it's a cached function\n   * e.g. wrapped in `React.cache` to avoid unnecessary computations\n   */\n  ctx: TRoot['ctx'] | (() => MaybePromise<TRoot['ctx']>),\n  options?: {\n    onError?: RouterCallerErrorHandler<TRoot['ctx']>;\n    signal?: AbortSignal;\n  },\n) => DecorateRouterRecord<TRecord>;\n\n/**\n * @internal\n */\nconst lazyMarker = 'lazyMarker' as 'lazyMarker' & {\n  __brand: 'lazyMarker';\n};\nexport type Lazy<TAny> = (() => Promise<TAny>) & { [lazyMarker]: true };\n\ntype LazyLoader<TAny> = {\n  load: () => Promise<void>;\n  ref: Lazy<TAny>;\n};\n\nfunction once<T>(fn: () => T): () => T {\n  const uncalled = Symbol();\n  let result: T | typeof uncalled = uncalled;\n  return (): T => {\n    if (result === uncalled) {\n      result = fn();\n    }\n    return result;\n  };\n}\n\n/**\n * Lazy load a router\n * @see https://trpc.io/docs/server/merging-routers#lazy-load\n */\nexport function lazy<TRouter extends AnyRouter>(\n  importRouter: () => Promise<\n    | TRouter\n    | {\n        [key: string]: TRouter;\n      }\n  >,\n): Lazy<NoInfer<TRouter>> {\n  async function resolve(): Promise<TRouter> {\n    const mod = await importRouter();\n\n    // if the module is a router, return it\n    if (isRouter(mod)) {\n      return mod;\n    }\n\n    const routers = Object.values(mod);\n\n    if (routers.length !== 1 || !isRouter(routers[0])) {\n      throw new Error(\n        \"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\",\n      );\n    }\n\n    return routers[0];\n  }\n\n  (resolve as Lazy<NoInfer<TRouter>>)[lazyMarker] = true as const;\n\n  return resolve as Lazy<NoInfer<TRouter>>;\n}\n\nfunction isLazy<TAny>(input: unknown): input is Lazy<TAny> {\n  return typeof input === 'function' && lazyMarker in input;\n}\n\n/**\n * @internal\n */\nexport interface RouterDef<\n  TRoot extends AnyRootTypes,\n  TRecord extends RouterRecord,\n> {\n  _config: RootConfig<TRoot>;\n  router: true;\n  procedure?: never;\n  procedures: TRecord;\n  record: TRecord;\n  lazy: Record<string, LazyLoader<AnyRouter>>;\n}\n\nexport interface Router<\n  TRoot extends AnyRootTypes,\n  TRecord extends RouterRecord,\n> {\n  _def: RouterDef<TRoot, TRecord>;\n  /**\n   * @see https://trpc.io/docs/v11/server/server-side-calls\n   */\n  createCaller: RouterCaller<TRoot, TRecord>;\n}\n\nexport type BuiltRouter<\n  TRoot extends AnyRootTypes,\n  TRecord extends RouterRecord,\n> = Router<TRoot, TRecord> & TRecord;\n\nexport interface RouterBuilder<TRoot extends AnyRootTypes> {\n  <TIn extends CreateRouterOptions>(\n    _: TIn,\n  ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TIn>>;\n}\n\nexport type AnyRouter = Router<any, any>;\n\nexport type inferRouterRootTypes<TRouter extends AnyRouter> =\n  TRouter['_def']['_config']['$types'];\n\nexport type inferRouterContext<TRouter extends AnyRouter> =\n  inferRouterRootTypes<TRouter>['ctx'];\nexport type inferRouterError<TRouter extends AnyRouter> =\n  inferRouterRootTypes<TRouter>['errorShape'];\nexport type inferRouterMeta<TRouter extends AnyRouter> =\n  inferRouterRootTypes<TRouter>['meta'];\n\nfunction isRouter(value: unknown): value is AnyRouter {\n  return (\n    isObject(value) && isObject(value['_def']) && 'router' in value['_def']\n  );\n}\n\nconst emptyRouter = {\n  _ctx: null as any,\n  _errorShape: null as any,\n  _meta: null as any,\n  queries: {},\n  mutations: {},\n  subscriptions: {},\n  errorFormatter: defaultFormatter,\n  transformer: defaultTransformer,\n};\n\n/**\n * Reserved words that can't be used as router or procedure names\n */\nconst reservedWords = [\n  /**\n   * Then is a reserved word because otherwise we can't return a promise that returns a Proxy\n   * since JS will think that `.then` is something that exists\n   */\n  'then',\n  /**\n   * `fn.call()` and `fn.apply()` are reserved words because otherwise we can't call a function using `.call` or `.apply`\n   */\n  'call',\n  'apply',\n];\n\n/** @internal */\nexport type CreateRouterOptions = {\n  [key: string]:\n    AnyProcedure | AnyRouter | CreateRouterOptions | Lazy<AnyRouter>;\n};\n\n/** @internal */\nexport type DecorateCreateRouterOptions<\n  TRouterOptions extends CreateRouterOptions,\n> = {\n  [K in keyof TRouterOptions]: TRouterOptions[K] extends infer $Value\n    ? $Value extends AnyProcedure\n      ? $Value\n      : $Value extends Router<any, infer TRecord>\n        ? TRecord\n        : $Value extends Lazy<Router<any, infer TRecord>>\n          ? TRecord\n          : $Value extends CreateRouterOptions\n            ? DecorateCreateRouterOptions<$Value>\n            : never\n    : never;\n};\n\n/**\n * @internal\n */\nexport function createRouterFactory<TRoot extends AnyRootTypes>(\n  config: RootConfig<TRoot>,\n) {\n  function createRouterInner<TInput extends CreateRouterOptions>(\n    input: TInput,\n  ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>> {\n    const reservedWordsUsed = new Set(\n      Object.keys(input).filter((v) => reservedWords.includes(v)),\n    );\n    if (reservedWordsUsed.size > 0) {\n      throw new Error(\n        'Reserved words used in `router({})` call: ' +\n          Array.from(reservedWordsUsed).join(', '),\n      );\n    }\n\n    const procedures: Record<string, AnyProcedure> = emptyObject();\n    const lazy: Record<string, LazyLoader<AnyRouter>> = emptyObject();\n\n    function createLazyLoader(opts: {\n      ref: Lazy<AnyRouter>;\n      path: readonly string[];\n      key: string;\n      aggregate: RouterRecord;\n    }): LazyLoader<AnyRouter> {\n      return {\n        ref: opts.ref,\n        load: once(async () => {\n          const router = await opts.ref();\n          const lazyPath = [...opts.path, opts.key];\n          const lazyKey = lazyPath.join('.');\n\n          opts.aggregate[opts.key] = step(router._def.record, lazyPath);\n\n          delete lazy[lazyKey];\n\n          // add lazy loaders for nested routers\n          for (const [nestedKey, nestedItem] of Object.entries(\n            router._def.lazy,\n          )) {\n            const nestedRouterKey = [...lazyPath, nestedKey].join('.');\n\n            // console.log('adding lazy', nestedRouterKey);\n            lazy[nestedRouterKey] = createLazyLoader({\n              ref: nestedItem.ref,\n              path: lazyPath,\n              key: nestedKey,\n              aggregate: opts.aggregate[opts.key] as RouterRecord,\n            });\n          }\n        }),\n      };\n    }\n\n    function step(from: CreateRouterOptions, path: readonly string[] = []) {\n      const aggregate: RouterRecord = emptyObject();\n      for (const [key, item] of Object.entries(from ?? {})) {\n        if (isLazy(item)) {\n          lazy[[...path, key].join('.')] = createLazyLoader({\n            path,\n            ref: item,\n            key,\n            aggregate,\n          });\n          continue;\n        }\n        if (isRouter(item)) {\n          aggregate[key] = step(item._def.record, [...path, key]);\n          continue;\n        }\n        if (!isProcedure(item)) {\n          // RouterRecord\n          aggregate[key] = step(item, [...path, key]);\n          continue;\n        }\n\n        const newPath = [...path, key].join('.');\n\n        if (procedures[newPath]) {\n          throw new Error(`Duplicate key: ${newPath}`);\n        }\n\n        procedures[newPath] = item;\n        aggregate[key] = item;\n      }\n\n      return aggregate;\n    }\n    const record = step(input);\n\n    const _def: AnyRouter['_def'] = {\n      _config: config,\n      router: true,\n      procedures,\n      lazy,\n      ...emptyRouter,\n      record,\n    };\n\n    const router: BuiltRouter<TRoot, {}> = {\n      ...(record as {}),\n      _def,\n      createCaller: createCallerFactory<TRoot>()({\n        _def,\n      }),\n    };\n    return router as BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>>;\n  }\n\n  return createRouterInner;\n}\n\nfunction isProcedure(\n  procedureOrRouter: ValueOf<CreateRouterOptions>,\n): procedureOrRouter is AnyProcedure {\n  return typeof procedureOrRouter === 'function';\n}\n\n/**\n * @internal\n */\nexport async function getProcedureAtPath(\n  router: Pick<Router<any, any>, '_def'>,\n  path: string,\n): Promise<AnyProcedure | null> {\n  const { _def } = router;\n  let procedure = _def.procedures[path];\n\n  while (!procedure) {\n    const key = Object.keys(_def.lazy).find(\n      (key) => path === key || path.startsWith(key + '.'),\n    );\n    // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);\n\n    if (!key) {\n      return null;\n    }\n    // console.log('loading', key, '.......');\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    const lazyRouter = _def.lazy[key]!;\n    await lazyRouter.load();\n\n    procedure = _def.procedures[path];\n  }\n\n  return procedure;\n}\n\n/**\n * @internal\n */\nexport async function callProcedure(\n  opts: ProcedureCallOptions<unknown> & {\n    router: AnyRouter;\n    allowMethodOverride?: boolean;\n  },\n) {\n  const { type, path } = opts;\n  const proc = await getProcedureAtPath(opts.router, path);\n  if (\n    !proc ||\n    !isProcedure(proc) ||\n    (proc._def.type !== type && !opts.allowMethodOverride)\n  ) {\n    throw new TRPCError({\n      code: 'NOT_FOUND',\n      message: `No \"${type}\"-procedure on path \"${path}\"`,\n    });\n  }\n\n  /* istanbul ignore if -- @preserve */\n  if (\n    proc._def.type !== type &&\n    opts.allowMethodOverride &&\n    proc._def.type === 'subscription'\n  ) {\n    throw new TRPCError({\n      code: 'METHOD_NOT_SUPPORTED',\n      message: `Method override is not supported for subscriptions`,\n    });\n  }\n\n  return proc(opts);\n}\n\nexport interface RouterCallerFactory<TRoot extends AnyRootTypes> {\n  <TRecord extends RouterRecord>(\n    router: Pick<Router<TRoot, TRecord>, '_def'>,\n  ): RouterCaller<TRoot, TRecord>;\n}\n\nexport function createCallerFactory<\n  TRoot extends AnyRootTypes,\n>(): RouterCallerFactory<TRoot> {\n  return function createCallerInner<TRecord extends RouterRecord>(\n    router: Pick<Router<TRoot, TRecord>, '_def'>,\n  ): RouterCaller<TRoot, TRecord> {\n    const { _def } = router;\n    type Context = TRoot['ctx'];\n\n    return function createCaller(ctxOrCallback, opts) {\n      return createRecursiveProxy<ReturnType<RouterCaller<any, any>>>(\n        async (innerOpts) => {\n          const { path, args } = innerOpts;\n          const fullPath = path.join('.');\n\n          if (path.length === 1 && path[0] === '_def') {\n            return _def;\n          }\n\n          const procedure = await getProcedureAtPath(router, fullPath);\n\n          let ctx: Context | undefined = undefined;\n          try {\n            if (!procedure) {\n              throw new TRPCError({\n                code: 'NOT_FOUND',\n                message: `No procedure found on path \"${path}\"`,\n              });\n            }\n            ctx = isFunction(ctxOrCallback)\n              ? await Promise.resolve(ctxOrCallback())\n              : ctxOrCallback;\n\n            return await procedure({\n              path: fullPath,\n              getRawInput: async () => args[0],\n              ctx,\n              type: procedure._def.type,\n              signal: opts?.signal,\n              batchIndex: 0,\n            });\n          } catch (cause) {\n            opts?.onError?.({\n              ctx,\n              error: getTRPCErrorFromUnknown(cause),\n              input: args[0],\n              path: fullPath,\n              type: procedure?._def.type ?? 'unknown',\n            });\n            throw cause;\n          }\n        },\n      );\n    };\n  };\n}\n\n/** @internal */\nexport type MergeRouters<\n  TRouters extends AnyRouter[],\n  TRoot extends AnyRootTypes = TRouters[0]['_def']['_config']['$types'],\n  TRecord extends RouterRecord = {},\n> = TRouters extends [\n  infer Head extends AnyRouter,\n  ...infer Tail extends AnyRouter[],\n]\n  ? MergeRouters<Tail, TRoot, Head['_def']['record'] & TRecord>\n  : BuiltRouter<TRoot, TRecord>;\n\nexport function mergeRouters<TRouters extends AnyRouter[]>(\n  ...routerList: [...TRouters]\n): MergeRouters<TRouters> {\n  const record = mergeWithoutOverrides(\n    {},\n    ...routerList.map((r) => r._def.record),\n  );\n  const errorFormatter = routerList.reduce(\n    (currentErrorFormatter, nextRouter) => {\n      if (\n        nextRouter._def._config.errorFormatter &&\n        nextRouter._def._config.errorFormatter !== defaultFormatter\n      ) {\n        if (\n          currentErrorFormatter !== defaultFormatter &&\n          currentErrorFormatter !== nextRouter._def._config.errorFormatter\n        ) {\n          throw new Error('You seem to have several error formatters');\n        }\n        return nextRouter._def._config.errorFormatter;\n      }\n      return currentErrorFormatter;\n    },\n    defaultFormatter,\n  );\n\n  const transformer = routerList.reduce((prev, current) => {\n    if (\n      current._def._config.transformer &&\n      current._def._config.transformer !== defaultTransformer\n    ) {\n      if (\n        prev !== defaultTransformer &&\n        prev !== current._def._config.transformer\n      ) {\n        throw new Error('You seem to have several transformers');\n      }\n      return current._def._config.transformer;\n    }\n    return prev;\n  }, defaultTransformer);\n\n  const router = createRouterFactory({\n    errorFormatter,\n    transformer,\n    isDev: routerList.every((r) => r._def._config.isDev),\n    allowOutsideOfServer: routerList.every(\n      (r) => r._def._config.allowOutsideOfServer,\n    ),\n    isServer: routerList.every((r) => r._def._config.isServer),\n    $types: routerList[0]?._def._config.$types,\n    sse: routerList[0]?._def._config.sse,\n  })(record);\n\n  return router as MergeRouters<TRouters>;\n}\n","const trackedSymbol = Symbol();\n\ntype TrackedId = string & {\n  __brand: 'TrackedId';\n};\nexport type TrackedEnvelope<TData> = [TrackedId, TData, typeof trackedSymbol];\n\nexport interface TrackedData<TData> {\n  /**\n   * The id of the message to keep track of in case the connection gets lost\n   */\n  id: string;\n  /**\n   * The data field of the message\n   */\n  data: TData;\n}\n/**\n * Produce a typed server-sent event message\n * @deprecated use `tracked(id, data)` instead\n */\nexport function sse<TData>(event: { id: string; data: TData }) {\n  return tracked(event.id, event.data);\n}\n\nexport function isTrackedEnvelope<TData>(\n  value: unknown,\n): value is TrackedEnvelope<TData> {\n  return Array.isArray(value) && value[2] === trackedSymbol;\n}\n\n/**\n * Automatically track an event so that it can be resumed from a given id if the connection is lost\n */\nexport function tracked<TData>(\n  id: string,\n  data: TData,\n): TrackedEnvelope<TData> {\n  if (id === '') {\n    // This limitation could be removed by using different SSE event names / channels for tracked event and non-tracked event\n    throw new Error(\n      '`id` must not be an empty string as empty string is the same as not setting the id at all',\n    );\n  }\n  return [id as TrackedId, data, trackedSymbol];\n}\n\nexport type inferTrackedOutput<TData> =\n  TData extends TrackedEnvelope<infer $Data> ? TrackedData<$Data> : TData;\n"],"mappings":";;;AA4CA,MAAa,oBAA8C,EAAE,YAAY;CACvE,OAAO;AACT;;;AC3CA,IAAM,oBAAN,cAAgC,MAAM;CAGpC,YAAY,OAAe;EACzB,MAAM,WAAW,KAAK,CAAC;EACvB,OAAO,OAAO,MAAM,KAAK;CAC3B;AACF;AAEA,SAAS,WAAW,OAAe;CACjC,IAAI,aAAa,OAAO,OAAO,OAAO,MAAM,OAAO;AAGrD;AAEA,SAAgB,oBAAoB,OAAmC;CACrE,IAAI,iBAAiB,OACnB,OAAO;CAGT,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,eAAe,SAAS,cAAc,UAAU,MAC3D;CAIF,IAAI,SAAS,UAEX,OAAO,IAAI,MAAM,OAAO,KAAK,CAAC;CAIhC,IAAI,SAAS,KAAK,GAChB,OAAO,IAAI,kBAAkB,KAAK;AAItC;AAEA,SAAgB,wBAAwB,OAA2B;CACjE,IAAI,iBAAiB,WACnB,OAAO;CAET,IAAI,iBAAiB,SAAS,MAAM,SAAS,aAE3C,OAAO;CAGT,MAAM,YAAY,IAAI,UAAU;EAC9B,M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