@trpc/server 11.22.2-canary.9.85bcf328a → 11.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -8
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- package/dist/ws-DJ2SSChC.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asyncGeneratorDelegate-FcEJT04i.mjs","names":[],"sources":["../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 { 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 if (isErrorLike(cause)) {\n if (typeof cause.name === 'string') this.name = cause.name;\n if (typeof cause.stack === 'string') this.stack = cause.stack;\n }\n }\n}\n\nfunction getMessage(cause: object) {\n if ('message' in cause) return String(cause.message);\n\n return undefined;\n}\n\n/**\n * Errors from another realm (e.g. `node:vm`, iframes) fail `instanceof Error`\n * but still carry the `[object Error]` brand.\n */\nfunction isErrorLike(value: unknown): value is Error {\n return (\n value instanceof Error ||\n Object.prototype.toString.call(value) === '[object Error]'\n );\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 (isErrorLike(cause) && 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 path: readonly string[];\n key: string;\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\nfunction getRouterInput(router: AnyRouter) {\n const input = Object.assign(\n emptyObject<CreateRouterOptions>(),\n router._def.record,\n );\n\n for (const loader of Object.values(router._def.lazy)) {\n let record = input;\n for (const key of loader.path) {\n record = record[key] = Object.assign(\n emptyObject<CreateRouterOptions>(),\n record[key],\n );\n }\n record[loader.key] = loader.ref;\n }\n\n return input;\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 path: opts.path,\n key: opts.key,\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(getRouterInput(router), lazyPath);\n\n delete lazy[lazyKey];\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(getRouterInput(item), [...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 ...[...new Set(routerList)].map((r) => getRouterInput(r)),\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":";;;AAGA,IAAM,oBAAN,cAAgC,MAAM;CAGpC,YAAY,OAAe;EACzB,MAAM,WAAW,KAAK,CAAC;EACvB,OAAO,OAAO,MAAM,KAAK;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AAK,QAAQ;EACpC,MAAA,gBAAK,WAAW,QAAA,QAAA,kBAAA,KAAA,IAAA,KAAA,IAAA,cAAI,KAAK,QAAQ;CACnC,CAAC,CAAC,CAAC,MAES;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5jBA,MAAM,gBAAgB,OAAO;;;;;AAqB7B,SAAgB,IAAW,OAAoC;CAC7D,OAAO,QAAQ,MAAM,IAAI,MAAM,IAAI;AACrC;AAEA,SAAgB,kBACd,OACiC;CACjC,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO;AAC9C;;;;AAKA,SAAgB,QACd,IACA,MACwB;CACxB,IAAI,OAAO,IAET,MAAM,IAAI,MACR,2FACF;CAEF,OAAO;EAAC;EAAiB;EAAM;CAAa;AAC9C"}
|
|
1
|
+
{"version":3,"file":"asyncGeneratorDelegate-FcEJT04i.mjs","names":[],"sources":["../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 { 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 if (isErrorLike(cause)) {\n if (typeof cause.name === 'string') this.name = cause.name;\n if (typeof cause.stack === 'string') this.stack = cause.stack;\n }\n }\n}\n\nfunction getMessage(cause: object) {\n if ('message' in cause) return String(cause.message);\n\n return undefined;\n}\n\n/**\n * Errors from another realm (e.g. `node:vm`, iframes) fail `instanceof Error`\n * but still carry the `[object Error]` brand.\n */\nfunction isErrorLike(value: unknown): value is Error {\n return (\n value instanceof Error ||\n Object.prototype.toString.call(value) === '[object Error]'\n );\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 // oxlint-disable-next-line typescript/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 (isErrorLike(cause) && cause.stack) {\n trpcError.stack = cause.stack;\n }\n\n return trpcError;\n}\n\nexport class TRPCError extends Error {\n // oxlint-disable-next-line typescript/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 // oxlint-disable-next-line typescript/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\n | TRPCResponse[]\n | TRPCResponseMessage\n | 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 path: readonly string[];\n key: string;\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\n | AnyRouter\n | CreateRouterOptions\n | 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\nfunction getRouterInput(router: AnyRouter) {\n const input = Object.assign(\n emptyObject<CreateRouterOptions>(),\n router._def.record,\n );\n\n for (const loader of Object.values(router._def.lazy)) {\n let record = input;\n for (const key of loader.path) {\n record = record[key] = Object.assign(\n emptyObject<CreateRouterOptions>(),\n record[key],\n );\n }\n record[loader.key] = loader.ref;\n }\n\n return input;\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 path: opts.path,\n key: opts.key,\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(getRouterInput(router), lazyPath);\n\n delete lazy[lazyKey];\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(getRouterInput(item), [...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 // oxlint-disable-next-line typescript/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 ...[...new Set(routerList)].map((r) => getRouterInput(r)),\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":";;;AAGA,IAAM,oBAAN,cAAgC,MAAM;CAGpC,YAAY,OAAe;EACzB,MAAM,WAAW,KAAK,CAAC;EACvB,OAAO,OAAO,MAAM,KAAK;EAEzB,IAAI,YAAY,KAAK,GAAG;GACtB,IAAI,OAAO,MAAM,SAAS,UAAU,KAAK,OAAO,MAAM;GACtD,IAAI,OAAO,MAAM,UAAU,UAAU,KAAK,QAAQ,MAAM;EAC1D;CACF;AACF;AAEA,SAAS,WAAW,OAAe;CACjC,IAAI,aAAa,OAAO,OAAO,OAAO,MAAM,OAAO;AAGrD;;;;;AAMA,SAAS,YAAY,OAAgC;CACnD,OACE,iBAAiB,SACjB,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AAE9C;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,MAAM;EACN;CACF,CAAC;CAGD,IAAI,YAAY,KAAK,KAAK,MAAM,OAC9B,UAAU,QAAQ,MAAM;CAG1B,OAAO;AACT;AAEA,IAAa,YAAb,cAA+B,MAAM;CAMnC,YAAY,MAIT;;EACD,MAAM,QAAQ,oBAAoB,KAAK,KAAK;EAC5C,MAAM,WAAA,QAAA,gBAAU,KAAK,aAAA,QAAA,kBAAA,K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,WAAW,OAAO,MAAM,EAAE,KAAK,QAAQ,KAAK;EACnD,sBAAsB,WAAW,OAC9B,MAAM,EAAE,KAAK,QAAQ,oBACxB;EACA,UAAU,WAAW,OAAO,MAAM,EAAE,KAAK,QAAQ,QAAQ;EACzD,SAAA,eAAQ,WAAW,QAAA,QAAA,iBAAA,KAAA,IAAA,KAAA,IAAA,aAAI,KAAK,QAAQ;EACpC,MAAA,gBAAK,WAAW,QAAA,QAAA,kBAAA,KAAA,IAAA,KAAA,IAAA,cAAI,KAAK,QAAQ;CACnC,CAAC,CAAC,CAAC,MAES;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/jBA,MAAM,gBAAgB,OAAO;;;;;AAqB7B,SAAgB,IAAW,OAAoC;CAC7D,OAAO,QAAQ,MAAM,IAAI,MAAM,IAAI;AACrC;AAEA,SAAgB,kBACd,OACiC;CACjC,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO;AAC9C;;;;AAKA,SAAgB,QACd,IACA,MACwB;CACxB,IAAI,OAAO,IAET,MAAM,IAAI,MACR,2FACF;CAEF,OAAO;EAAC;EAAiB;EAAM;CAAa;AAC9C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codes-C9N0z0an.mjs","names":[],"sources":["../src/unstable-core-do-not-import/utils.ts","../src/unstable-core-do-not-import/rpc/codes.ts"],"sourcesContent":["/** @internal */\nexport type UnsetMarker = 'unsetMarker' & {\n __brand: 'unsetMarker';\n};\n\n/**\n * Ensures there are no duplicate keys when building a procedure.\n * @internal\n */\nexport function mergeWithoutOverrides<TType extends Record<string, unknown>>(\n obj1: TType,\n ...objs: Partial<TType>[]\n): TType {\n const newObj: TType = Object.assign(emptyObject(), obj1);\n\n for (const overrides of objs) {\n for (const key in overrides) {\n if (key in newObj && newObj[key] !== overrides[key]) {\n throw new Error(`Duplicate key ${key}`);\n }\n newObj[key as keyof TType] = overrides[key] as TType[keyof TType];\n }\n }\n return newObj;\n}\n\n/**\n * Check that value is object\n * @internal\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return !!value && !Array.isArray(value) && typeof value === 'object';\n}\n\ntype AnyFn = ((...args: any[]) => unknown) & Record<keyof any, unknown>;\nexport function isFunction(fn: unknown): fn is AnyFn {\n return typeof fn === 'function';\n}\n\n/**\n * Create an object without inheriting anything from `Object.prototype`\n * @internal\n */\nexport function emptyObject<TObj extends Record<string, unknown>>(): TObj {\n return Object.create(null);\n}\n\nconst asyncIteratorsSupported =\n typeof Symbol === 'function' && !!Symbol.asyncIterator;\n\nexport function isAsyncIterable<TValue>(\n value: unknown,\n): value is AsyncIterable<TValue> {\n return (\n asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value\n );\n}\n\n/**\n * Run an IIFE\n */\nexport const run = <TValue>(fn: () => TValue): TValue => fn();\n\n//
|
|
1
|
+
{"version":3,"file":"codes-C9N0z0an.mjs","names":[],"sources":["../src/unstable-core-do-not-import/utils.ts","../src/unstable-core-do-not-import/rpc/codes.ts"],"sourcesContent":["/** @internal */\nexport type UnsetMarker = 'unsetMarker' & {\n __brand: 'unsetMarker';\n};\n\n/**\n * Ensures there are no duplicate keys when building a procedure.\n * @internal\n */\nexport function mergeWithoutOverrides<TType extends Record<string, unknown>>(\n obj1: TType,\n ...objs: Partial<TType>[]\n): TType {\n const newObj: TType = Object.assign(emptyObject(), obj1);\n\n for (const overrides of objs) {\n for (const key in overrides) {\n if (key in newObj && newObj[key] !== overrides[key]) {\n throw new Error(`Duplicate key ${key}`);\n }\n newObj[key as keyof TType] = overrides[key] as TType[keyof TType];\n }\n }\n return newObj;\n}\n\n/**\n * Check that value is object\n * @internal\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return !!value && !Array.isArray(value) && typeof value === 'object';\n}\n\ntype AnyFn = ((...args: any[]) => unknown) & Record<keyof any, unknown>;\nexport function isFunction(fn: unknown): fn is AnyFn {\n return typeof fn === 'function';\n}\n\n/**\n * Create an object without inheriting anything from `Object.prototype`\n * @internal\n */\nexport function emptyObject<TObj extends Record<string, unknown>>(): TObj {\n return Object.create(null);\n}\n\nconst asyncIteratorsSupported =\n typeof Symbol === 'function' && !!Symbol.asyncIterator;\n\nexport function isAsyncIterable<TValue>(\n value: unknown,\n): value is AsyncIterable<TValue> {\n return (\n asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value\n );\n}\n\n/**\n * Run an IIFE\n */\nexport const run = <TValue>(fn: () => TValue): TValue => fn();\n\n// oxlint-disable-next-line typescript/no-empty-function\nexport function noop(): void {}\n\nexport function identity<T>(it: T): T {\n return it;\n}\n\n/**\n * Generic runtime assertion function. Throws, if the condition is not `true`.\n *\n * Can be used as a slightly less dangerous variant of type assertions. Code\n * mistakes would be revealed at runtime then (hopefully during testing).\n */\nexport function assert(\n condition: boolean,\n msg = 'no additional info',\n): asserts condition {\n if (!condition) {\n throw new Error(`AssertionError: ${msg}`);\n }\n}\n\nexport function assertNever(value: never): never {\n throw new Error(`AssertionError: unexpected value ${String(value)}`);\n}\n\nexport function sleep(ms = 0): Promise<void> {\n return new Promise<void>((res) => setTimeout(res, ms));\n}\n\n/**\n * Ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function abortSignalsAnyPonyfill(signals: AbortSignal[]): AbortSignal {\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any(signals);\n }\n\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal.aborted) {\n trigger();\n break;\n }\n signal.addEventListener('abort', trigger, { once: true });\n }\n\n return ac.signal;\n\n function trigger() {\n ac.abort();\n for (const signal of signals) {\n signal.removeEventListener('abort', trigger);\n }\n }\n}\n","import type { InvertKeyValue, ValueOf } from '../types';\n\n// reference: https://www.jsonrpc.org/specification\n\n/**\n * JSON-RPC 2.0 Error codes\n *\n * `-32000` to `-32099` are reserved for implementation-defined server-errors.\n * For tRPC we're copying the last digits of HTTP 4XX errors.\n */\nexport const TRPC_ERROR_CODES_BY_KEY = {\n /**\n * Invalid JSON was received by the server.\n * An error occurred on the server while parsing the JSON text.\n */\n PARSE_ERROR: -32700,\n /**\n * The JSON sent is not a valid Request object.\n */\n BAD_REQUEST: -32600, // 400\n\n // Internal JSON-RPC error\n INTERNAL_SERVER_ERROR: -32603, // 500\n NOT_IMPLEMENTED: -32603, // 501\n BAD_GATEWAY: -32603, // 502\n SERVICE_UNAVAILABLE: -32603, // 503\n GATEWAY_TIMEOUT: -32603, // 504\n\n // Implementation specific errors\n UNAUTHORIZED: -32001, // 401\n PAYMENT_REQUIRED: -32002, // 402\n FORBIDDEN: -32003, // 403\n NOT_FOUND: -32004, // 404\n METHOD_NOT_SUPPORTED: -32005, // 405\n TIMEOUT: -32008, // 408\n CONFLICT: -32009, // 409\n PRECONDITION_FAILED: -32012, // 412\n PAYLOAD_TOO_LARGE: -32013, // 413\n UNSUPPORTED_MEDIA_TYPE: -32015, // 415\n UNPROCESSABLE_CONTENT: -32022, // 422\n PRECONDITION_REQUIRED: -32028, // 428\n TOO_MANY_REQUESTS: -32029, // 429\n CLIENT_CLOSED_REQUEST: -32099, // 499\n} as const;\n\n// pure\nexport const TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n> = {\n [-32700]: 'PARSE_ERROR',\n [-32600]: 'BAD_REQUEST',\n [-32603]: 'INTERNAL_SERVER_ERROR',\n [-32001]: 'UNAUTHORIZED',\n [-32002]: 'PAYMENT_REQUIRED',\n [-32003]: 'FORBIDDEN',\n [-32004]: 'NOT_FOUND',\n [-32005]: 'METHOD_NOT_SUPPORTED',\n [-32008]: 'TIMEOUT',\n [-32009]: 'CONFLICT',\n [-32012]: 'PRECONDITION_FAILED',\n [-32013]: 'PAYLOAD_TOO_LARGE',\n [-32015]: 'UNSUPPORTED_MEDIA_TYPE',\n [-32022]: 'UNPROCESSABLE_CONTENT',\n [-32028]: 'PRECONDITION_REQUIRED',\n [-32029]: 'TOO_MANY_REQUESTS',\n [-32099]: 'CLIENT_CLOSED_REQUEST',\n};\n\nexport type TRPC_ERROR_CODE_NUMBER = ValueOf<typeof TRPC_ERROR_CODES_BY_KEY>;\nexport type TRPC_ERROR_CODE_KEY = keyof typeof TRPC_ERROR_CODES_BY_KEY;\n\n/**\n * tRPC error codes that are considered retryable\n * With out of the box SSE, the client will reconnect when these errors are encountered\n */\nexport const retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[] = [\n TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n];\n"],"mappings":";;;;;AASA,SAAgB,sBACd,MACA,GAAG,MACI;CACP,MAAM,SAAgB,OAAO,OAAO,YAAY,GAAG,IAAI;CAEvD,KAAK,MAAM,aAAa,MACtB,KAAK,MAAM,OAAO,WAAW;EAC3B,IAAI,OAAO,UAAU,OAAO,SAAS,UAAU,MAC7C,MAAM,IAAI,MAAM,iBAAiB,KAAK;EAExC,OAAO,OAAsB,UAAU;CACzC;CAEF,OAAO;AACT;;;;;AAMA,SAAgB,SAAS,OAAkD;CACzE,OAAO,CAAC,CAAC,SAAS,CAAC,MAAM,QAAQ,KAAK,KAAK,OAAO,UAAU;AAC9D;AAGA,SAAgB,WAAW,IAA0B;CACnD,OAAO,OAAO,OAAO;AACvB;;;;;AAMA,SAAgB,cAA0D;CACxE,OAAO,OAAO,OAAO,IAAI;AAC3B;AAEA,MAAM,0BACJ,OAAO,WAAW,cAAc,CAAC,CAAC,OAAO;AAE3C,SAAgB,gBACd,OACgC;CAChC,OACE,2BAA2B,SAAS,KAAK,KAAK,OAAO,iBAAiB;AAE1E;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S;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;AACZ;;;;;AASA,MAAa,oBAA8C;CACzD,wBAAwB;CACxB,wBAAwB;CACxB,wBAAwB;CACxB,wBAAwB;AAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getErrorShape-zlj81BiC.mjs","names":[],"sources":["../src/unstable-core-do-not-import/createProxy.ts","../src/unstable-core-do-not-import/http/getHTTPStatusCode.ts","../src/unstable-core-do-not-import/error/formatter.ts","../src/unstable-core-do-not-import/error/getErrorShape.ts"],"sourcesContent":["import { emptyObject } from './utils';\n\ninterface ProxyCallbackOptions {\n path: readonly string[];\n args: readonly unknown[];\n}\ntype ProxyCallback = (opts: ProxyCallbackOptions) => unknown;\n\nconst noop = () => {\n // noop\n};\n\nconst freezeIfAvailable = (obj: object) => {\n if (Object.freeze) {\n Object.freeze(obj);\n }\n};\n\nfunction createInnerProxy(\n callback: ProxyCallback,\n path: readonly string[],\n memo: Record<string, unknown>,\n) {\n const cacheKey = path.join('.');\n\n memo[cacheKey] ??= new Proxy(noop, {\n get(_obj, key) {\n if (typeof key !== 'string' || key === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return createInnerProxy(callback, [...path, key], memo);\n },\n apply(_1, _2, args) {\n const lastOfPath = path[path.length - 1];\n\n // React 19 may call valueOf / toString / toJSON when coercing a proxy\n // to a primitive (e.g. during rendering or logging). Return a debug\n // string so the coercion does not recurse into the proxy. This only\n // triggers for direct calls (proxy.toString()), not for chained access\n // (proxy.toString.query()), preserving route naming freedom.\n if (\n lastOfPath === 'valueOf' ||\n lastOfPath === 'toString' ||\n lastOfPath === 'toJSON'\n ) {\n const debugPath = path.slice(0, -1).join('.');\n return `tRPC.proxy(${debugPath})`;\n }\n\n let opts = { args, path };\n // special handling for e.g. `trpc.hello.call(this, 'there')` and `trpc.hello.apply(this, ['there'])\n if (lastOfPath === 'call') {\n opts = {\n args: args.length >= 2 ? [args[1]] : [],\n path: path.slice(0, -1),\n };\n } else if (lastOfPath === 'apply') {\n opts = {\n args: args.length >= 2 ? args[1] : [],\n path: path.slice(0, -1),\n };\n }\n freezeIfAvailable(opts.args);\n freezeIfAvailable(opts.path);\n return callback(opts);\n },\n });\n\n return memo[cacheKey];\n}\n\n/**\n * Creates a proxy that calls the callback with the path and arguments\n *\n * @internal\n */\nexport const createRecursiveProxy = <TFaux = unknown>(\n callback: ProxyCallback,\n): TFaux => createInnerProxy(callback, [], emptyObject()) as TFaux;\n\n/**\n * Used in place of `new Proxy` where each handler will map 1 level deep to another value.\n *\n * @internal\n */\nexport const createFlatProxy = <TFaux>(\n callback: (path: keyof TFaux) => any,\n): TFaux => {\n return new Proxy(noop, {\n get(_obj, name) {\n if (name === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return callback(name as any);\n },\n }) as TFaux;\n};\n","import type { TRPCError } from '../error/TRPCError';\nimport type { TRPC_ERROR_CODES_BY_KEY, TRPCResponse } from '../rpc';\nimport { TRPC_ERROR_CODES_BY_NUMBER } from '../rpc';\nimport type { InvertKeyValue, ValueOf } from '../types';\nimport { isObject } from '../utils';\n\nexport const JSONRPC2_TO_HTTP_CODE: Record<\n keyof typeof TRPC_ERROR_CODES_BY_KEY,\n number\n> = {\n PARSE_ERROR: 400,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_SUPPORTED: 405,\n TIMEOUT: 408,\n CONFLICT: 409,\n PRECONDITION_FAILED: 412,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_CONTENT: 422,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n CLIENT_CLOSED_REQUEST: 499,\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n};\n\nexport const HTTP_CODE_TO_JSONRPC2: InvertKeyValue<\n typeof JSONRPC2_TO_HTTP_CODE\n> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 402: 'PAYMENT_REQUIRED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_SUPPORTED',\n 408: 'TIMEOUT',\n 409: 'CONFLICT',\n 412: 'PRECONDITION_FAILED',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'UNPROCESSABLE_CONTENT',\n 428: 'PRECONDITION_REQUIRED',\n 429: 'TOO_MANY_REQUESTS',\n 499: 'CLIENT_CLOSED_REQUEST',\n 500: 'INTERNAL_SERVER_ERROR',\n 501: 'NOT_IMPLEMENTED',\n 502: 'BAD_GATEWAY',\n 503: 'SERVICE_UNAVAILABLE',\n 504: 'GATEWAY_TIMEOUT',\n} as const;\n\nexport function getStatusCodeFromKey(\n code: keyof typeof TRPC_ERROR_CODES_BY_KEY,\n) {\n return JSONRPC2_TO_HTTP_CODE[code] ?? 500;\n}\n\nexport function getStatusKeyFromCode(\n code: keyof typeof HTTP_CODE_TO_JSONRPC2,\n): ValueOf<typeof HTTP_CODE_TO_JSONRPC2> {\n return HTTP_CODE_TO_JSONRPC2[code] ?? 'INTERNAL_SERVER_ERROR';\n}\n\nexport function getHTTPStatusCode(json: TRPCResponse | TRPCResponse[]) {\n const arr = Array.isArray(json) ? json : [json];\n const httpStatuses = new Set<number>(\n arr.map((res) => {\n if ('error' in res && isObject(res.error.data)) {\n if (typeof res.error.data?.['httpStatus'] === 'number') {\n return res.error.data['httpStatus'];\n }\n const code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];\n return getStatusCodeFromKey(code);\n }\n return 200;\n }),\n );\n\n if (httpStatuses.size !== 1) {\n return 207;\n }\n\n const httpStatus = httpStatuses.values().next().value;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return httpStatus!;\n}\n\nexport function getHTTPStatusCodeFromError(error: TRPCError) {\n return getStatusCodeFromKey(error.code);\n}\n","import { getHTTPStatusCodeFromError } from '../http/getHTTPStatusCode';\nimport type { ProcedureType } from '../procedure';\nimport type {\n TRPC_ERROR_CODE_KEY,\n TRPC_ERROR_CODE_NUMBER,\n TRPCErrorShape,\n} from '../rpc';\nimport { TRPC_ERROR_CODES_BY_KEY } from '../rpc';\nimport type { Overwrite, Simplify } from '../types';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport interface ErrorFormatterOptions<TContext> {\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TContext;\n shape: DefaultErrorShape;\n}\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (\n opts: ErrorFormatterOptions<TContext | undefined>,\n) => TShape;\n\n/**\n * @internal\n */\nexport type ProcedureErrorFormatter<\n TContext,\n TContextOverrides,\n TShape extends TRPCErrorShape | undefined | void,\n> = (\n opts: ErrorFormatterOptions<Simplify<Overwrite<TContext, TContextOverrides>>>,\n) => TShape;\n\n/**\n * @internal\n */\nexport type AnyProcedureErrorFormatter = ProcedureErrorFormatter<any, any, any>;\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\n/**\n * @internal\n */\nexport function getDefaultErrorShape(opts: {\n error: TRPCError;\n path: string | undefined;\n isDev: boolean;\n}): DefaultErrorShape {\n const shape: DefaultErrorShape = {\n message: opts.error.message,\n code: TRPC_ERROR_CODES_BY_KEY[opts.error.code],\n data: {\n code: opts.error.code,\n httpStatus: getHTTPStatusCodeFromError(opts.error),\n },\n };\n if (opts.isDev && typeof opts.error.stack === 'string') {\n shape.data.stack = opts.error.stack;\n }\n if (typeof opts.path === 'string') {\n shape.data.path = opts.path;\n }\n return shape;\n}\n\nconst formattedShapeSymbol = Symbol('trpc_formattedErrorShape');\n\n/**\n * @internal\n */\nexport function setFormattedErrorShape(\n error: TRPCError,\n shape: TRPCErrorShape,\n): asserts error is TRPCError & { [formattedShapeSymbol]: TRPCErrorShape } {\n Object.defineProperty(error, formattedShapeSymbol, {\n value: shape,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * @internal\n */\nexport function getFormattedErrorShape(\n error: TRPCError,\n): TRPCErrorShape | undefined {\n if (isFormattedErrorShape(error)) {\n return error[formattedShapeSymbol];\n }\n\n return undefined;\n}\n\nexport function isFormattedErrorShape(\n error: TRPCError,\n): error is TRPCError & { [formattedShapeSymbol]: TRPCErrorShape } {\n return formattedShapeSymbol in error;\n}\n","import type { ProcedureType } from '../procedure';\nimport type { AnyRootTypes, RootConfig } from '../rootConfig';\nimport { getDefaultErrorShape, getFormattedErrorShape } from './formatter';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport function getErrorShape<TRoot extends AnyRootTypes>(opts: {\n config: RootConfig<TRoot>;\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TRoot['ctx'] | undefined;\n}): TRoot['errorShape'] {\n const { path, error, config } = opts;\n\n // a `.errors()` handler already created the final shape\n const formatted = getFormattedErrorShape(error);\n if (formatted !== undefined) {\n return formatted;\n }\n\n const shape = getDefaultErrorShape({ error, path, isDev: config.isDev });\n return config.errorFormatter({ ...opts, shape });\n}\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ts","../src/unstable-core-do-not-import/http/getHTTPStatusCode.ts","../src/unstable-core-do-not-import/error/formatter.ts","../src/unstable-core-do-not-import/error/getErrorShape.ts"],"sourcesContent":["import { emptyObject } from './utils';\n\ninterface ProxyCallbackOptions {\n path: readonly string[];\n args: readonly unknown[];\n}\ntype ProxyCallback = (opts: ProxyCallbackOptions) => unknown;\n\nconst noop = () => {\n // noop\n};\n\nconst freezeIfAvailable = (obj: object) => {\n if (Object.freeze) {\n Object.freeze(obj);\n }\n};\n\nfunction createInnerProxy(\n callback: ProxyCallback,\n path: readonly string[],\n memo: Record<string, unknown>,\n) {\n const cacheKey = path.join('.');\n\n memo[cacheKey] ??= new Proxy(noop, {\n get(_obj, key) {\n if (typeof key !== 'string' || key === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return createInnerProxy(callback, [...path, key], memo);\n },\n apply(_1, _2, args) {\n const lastOfPath = path[path.length - 1];\n\n // React 19 may call valueOf / toString / toJSON when coercing a proxy\n // to a primitive (e.g. during rendering or logging). Return a debug\n // string so the coercion does not recurse into the proxy. This only\n // triggers for direct calls (proxy.toString()), not for chained access\n // (proxy.toString.query()), preserving route naming freedom.\n if (\n lastOfPath === 'valueOf' ||\n lastOfPath === 'toString' ||\n lastOfPath === 'toJSON'\n ) {\n const debugPath = path.slice(0, -1).join('.');\n return `tRPC.proxy(${debugPath})`;\n }\n\n let opts = { args, path };\n // special handling for e.g. `trpc.hello.call(this, 'there')` and `trpc.hello.apply(this, ['there'])\n if (lastOfPath === 'call') {\n opts = {\n args: args.length >= 2 ? [args[1]] : [],\n path: path.slice(0, -1),\n };\n } else if (lastOfPath === 'apply') {\n opts = {\n args: args.length >= 2 ? args[1] : [],\n path: path.slice(0, -1),\n };\n }\n freezeIfAvailable(opts.args);\n freezeIfAvailable(opts.path);\n return callback(opts);\n },\n });\n\n return memo[cacheKey];\n}\n\n/**\n * Creates a proxy that calls the callback with the path and arguments\n *\n * @internal\n */\nexport const createRecursiveProxy = <TFaux = unknown>(\n callback: ProxyCallback,\n): TFaux => createInnerProxy(callback, [], emptyObject()) as TFaux;\n\n/**\n * Used in place of `new Proxy` where each handler will map 1 level deep to another value.\n *\n * @internal\n */\nexport const createFlatProxy = <TFaux>(\n callback: (path: keyof TFaux) => any,\n): TFaux => {\n return new Proxy(noop, {\n get(_obj, name) {\n if (name === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return callback(name as any);\n },\n }) as TFaux;\n};\n","import type { TRPCError } from '../error/TRPCError';\nimport type { TRPC_ERROR_CODES_BY_KEY, TRPCResponse } from '../rpc';\nimport { TRPC_ERROR_CODES_BY_NUMBER } from '../rpc';\nimport type { InvertKeyValue, ValueOf } from '../types';\nimport { isObject } from '../utils';\n\nexport const JSONRPC2_TO_HTTP_CODE: Record<\n keyof typeof TRPC_ERROR_CODES_BY_KEY,\n number\n> = {\n PARSE_ERROR: 400,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_SUPPORTED: 405,\n TIMEOUT: 408,\n CONFLICT: 409,\n PRECONDITION_FAILED: 412,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_CONTENT: 422,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n CLIENT_CLOSED_REQUEST: 499,\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n};\n\nexport const HTTP_CODE_TO_JSONRPC2: InvertKeyValue<\n typeof JSONRPC2_TO_HTTP_CODE\n> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 402: 'PAYMENT_REQUIRED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_SUPPORTED',\n 408: 'TIMEOUT',\n 409: 'CONFLICT',\n 412: 'PRECONDITION_FAILED',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'UNPROCESSABLE_CONTENT',\n 428: 'PRECONDITION_REQUIRED',\n 429: 'TOO_MANY_REQUESTS',\n 499: 'CLIENT_CLOSED_REQUEST',\n 500: 'INTERNAL_SERVER_ERROR',\n 501: 'NOT_IMPLEMENTED',\n 502: 'BAD_GATEWAY',\n 503: 'SERVICE_UNAVAILABLE',\n 504: 'GATEWAY_TIMEOUT',\n} as const;\n\nexport function getStatusCodeFromKey(\n code: keyof typeof TRPC_ERROR_CODES_BY_KEY,\n) {\n return JSONRPC2_TO_HTTP_CODE[code] ?? 500;\n}\n\nexport function getStatusKeyFromCode(\n code: keyof typeof HTTP_CODE_TO_JSONRPC2,\n): ValueOf<typeof HTTP_CODE_TO_JSONRPC2> {\n return HTTP_CODE_TO_JSONRPC2[code] ?? 'INTERNAL_SERVER_ERROR';\n}\n\nexport function getHTTPStatusCode(json: TRPCResponse | TRPCResponse[]) {\n const arr = Array.isArray(json) ? json : [json];\n const httpStatuses = new Set<number>(\n arr.map((res) => {\n if ('error' in res && isObject(res.error.data)) {\n if (typeof res.error.data?.['httpStatus'] === 'number') {\n return res.error.data['httpStatus'];\n }\n const code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];\n return getStatusCodeFromKey(code);\n }\n return 200;\n }),\n );\n\n if (httpStatuses.size !== 1) {\n return 207;\n }\n\n const httpStatus = httpStatuses.values().next().value;\n\n // oxlint-disable-next-line typescript/no-non-null-assertion\n return httpStatus!;\n}\n\nexport function getHTTPStatusCodeFromError(error: TRPCError) {\n return getStatusCodeFromKey(error.code);\n}\n","import { getHTTPStatusCodeFromError } from '../http/getHTTPStatusCode';\nimport type { ProcedureType } from '../procedure';\nimport type {\n TRPC_ERROR_CODE_KEY,\n TRPC_ERROR_CODE_NUMBER,\n TRPCErrorShape,\n} from '../rpc';\nimport { TRPC_ERROR_CODES_BY_KEY } from '../rpc';\nimport type { Overwrite, Simplify } from '../types';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport interface ErrorFormatterOptions<TContext> {\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TContext;\n shape: DefaultErrorShape;\n}\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (\n opts: ErrorFormatterOptions<TContext | undefined>,\n) => TShape;\n\n/**\n * @internal\n */\nexport type ProcedureErrorFormatter<\n TContext,\n TContextOverrides,\n TShape extends TRPCErrorShape | undefined | void,\n> = (\n opts: ErrorFormatterOptions<Simplify<Overwrite<TContext, TContextOverrides>>>,\n) => TShape;\n\n/**\n * @internal\n */\nexport type AnyProcedureErrorFormatter = ProcedureErrorFormatter<any, any, any>;\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\n/**\n * @internal\n */\nexport function getDefaultErrorShape(opts: {\n error: TRPCError;\n path: string | undefined;\n isDev: boolean;\n}): DefaultErrorShape {\n const shape: DefaultErrorShape = {\n message: opts.error.message,\n code: TRPC_ERROR_CODES_BY_KEY[opts.error.code],\n data: {\n code: opts.error.code,\n httpStatus: getHTTPStatusCodeFromError(opts.error),\n },\n };\n if (opts.isDev && typeof opts.error.stack === 'string') {\n shape.data.stack = opts.error.stack;\n }\n if (typeof opts.path === 'string') {\n shape.data.path = opts.path;\n }\n return shape;\n}\n\nconst formattedShapeSymbol = Symbol('trpc_formattedErrorShape');\n\n/**\n * @internal\n */\nexport function setFormattedErrorShape(\n error: TRPCError,\n shape: TRPCErrorShape,\n): asserts error is TRPCError & { [formattedShapeSymbol]: TRPCErrorShape } {\n Object.defineProperty(error, formattedShapeSymbol, {\n value: shape,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * @internal\n */\nexport function getFormattedErrorShape(\n error: TRPCError,\n): TRPCErrorShape | undefined {\n if (isFormattedErrorShape(error)) {\n return error[formattedShapeSymbol];\n }\n\n return undefined;\n}\n\nexport function isFormattedErrorShape(\n error: TRPCError,\n): error is TRPCError & { [formattedShapeSymbol]: TRPCErrorShape } {\n return formattedShapeSymbol in error;\n}\n","import type { ProcedureType } from '../procedure';\nimport type { AnyRootTypes, RootConfig } from '../rootConfig';\nimport { getDefaultErrorShape, getFormattedErrorShape } from './formatter';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport function getErrorShape<TRoot extends AnyRootTypes>(opts: {\n config: RootConfig<TRoot>;\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TRoot['ctx'] | undefined;\n}): TRoot['errorShape'] {\n const { path, error, config } = opts;\n\n // a `.errors()` handler already created the final shape\n const formatted = getFormattedErrorShape(error);\n if (formatted !== undefined) {\n return formatted;\n }\n\n const shape = getDefaultErrorShape({ error, path, isDev: config.isDev });\n return config.errorFormatter({ ...opts, shape });\n}\n"],"mappings":";;AAQA,MAAM,aAAa,CAEnB;AAEA,MAAM,qBAAqB,QAAgB;CACzC,IAAI,OAAO,QACT,OAAO,OAAO,GAAG;AAErB;AAEA,SAAS,iBACP,UACA,MACA,MACA;;CACA,MAAM,WAAW,KAAK,KAAK,GAAG;CAE9B,CAAA,iBAAA,KAAK,eAAA,QAAA,mBAAA,KAAA,MAAL,KAAK,YAAc,IAAI,MAAM,MAAM;EACjC,IAAI,MAAM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D;CACF;CACA,IAAI,KAAK,SAAS,OAAO,KAAK,MAAM,UAAU,UAC5C,MAAM,KAAK,QAAQ,KAAK,MAAM;CAEhC,IAAI,OAAO,KAAK,SAAS,UACvB,MAAM,KAAK,OAAO,KAAK;CAEzB,OAAO;AACT;AAEA,MAAM,uBAAuB,OAAO,0BAA0B;;;;AAK9D,SAAgB,uBACd,OACA,OACyE;CACzE,OAAO,eAAe,OAAO,sBAAsB;EACjD,OAAO;EACP,YAAY;EACZ,cAAc;EACd,UAAU;CACZ,CAAC;AACH;;;;AAKA,SAAgB,uBACd,OAC4B;CAC5B,IAAI,sBAAsB,KAAK,GAC7B,OAAO,MAAM;AAIjB;AAEA,SAAgB,sBACd,OACiE;CACjE,OAAO,wBAAwB;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7HA,SAAgB,cAA0C,MAOlC;CACtB,MAAM,EAAE,MAAM,OAAO,WAAW;CAGhC,MAAM,YAAY,uBAAuB,KAAK;CAC9C,IAAI,cAAc,KAAA,GAChB,OAAO;CAGT,MAAM,QAAQ,qBAAqB;EAAE;EAAO;EAAM,OAAO,OAAO;CAAM,CAAC;CACvE,OAAO,OAAO,eAAA,eAAA,eAAA,CAAA,GAAoB,IAAA,GAAA,CAAA,GAAA,EAAM,MAAA,CAAM,CAAC;AACjD"}
|
package/dist/http.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_getErrorShape = require("./getErrorShape-hncV8cPE.cjs");
|
|
3
|
-
const require_resolveResponse = require("./resolveResponse-
|
|
3
|
+
const require_resolveResponse = require("./resolveResponse-CoGjFxK0.cjs");
|
|
4
4
|
const require_contentTypeParsers = require("./contentTypeParsers-B1e2ZNvN.cjs");
|
|
5
5
|
exports.getHTTPStatusCode = require_getErrorShape.getHTTPStatusCode;
|
|
6
6
|
exports.getHTTPStatusCodeFromError = require_getErrorShape.getHTTPStatusCodeFromError;
|
package/dist/http.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { d as getHTTPStatusCode, f as getHTTPStatusCodeFromError } from "./getErrorShape-zlj81BiC.mjs";
|
|
2
|
-
import { b as parseConnectionParamsFromString, t as resolveResponse, x as parseConnectionParamsFromUnknown } from "./resolveResponse-
|
|
2
|
+
import { b as parseConnectionParamsFromString, t as resolveResponse, x as parseConnectionParamsFromUnknown } from "./resolveResponse-DksrxZ2k.mjs";
|
|
3
3
|
import { t as octetInputParser } from "./contentTypeParsers-Bb-9hUEf.mjs";
|
|
4
4
|
export { getHTTPStatusCode, getHTTPStatusCodeFromError, octetInputParser, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, resolveResponse };
|
|
5
5
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initTRPC-RMeQIy9H.mjs","names":[],"sources":["../src/unstable-core-do-not-import/middleware.ts","../src/vendor/standard-schema-v1/error.ts","../src/unstable-core-do-not-import/parser.ts","../src/unstable-core-do-not-import/rootConfig.ts","../src/unstable-core-do-not-import/procedureBuilder.ts","../src/unstable-core-do-not-import/initTRPC.ts"],"sourcesContent":["import type { Observable } from '../observable';\nimport { isObservable, observable } from '../observable';\nimport type { AnyProcedureErrorFormatter } from './error/formatter';\nimport {\n getDefaultErrorShape,\n isFormattedErrorShape,\n setFormattedErrorShape,\n} from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type { ParseFn } from './parser';\nimport type { ProcedureType } from './procedure';\nimport type { GetRawInputFn, Overwrite, Simplify } from './types';\nimport { isAsyncIterable, isObject } from './utils';\n\n/** @internal */\nexport const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {\n __brand: 'middlewareMarker';\n};\ntype MiddlewareMarker = typeof middlewareMarker;\n\ninterface MiddlewareResultBase {\n /**\n * All middlewares should pass through their `next()`'s output.\n * Requiring this marker makes sure that can't be forgotten at compile-time.\n */\n readonly marker: MiddlewareMarker;\n}\n\ninterface MiddlewareOKResult<_TContextOverride> extends MiddlewareResultBase {\n ok: true;\n data: unknown;\n // this could be extended with `input`/`rawInput` later\n}\n\ninterface MiddlewareErrorResult<\n _TContextOverride,\n> extends MiddlewareResultBase {\n ok: false;\n error: TRPCError;\n}\n\n/**\n * @internal\n */\nexport type MiddlewareResult<_TContextOverride> =\n | MiddlewareErrorResult<_TContextOverride>\n | MiddlewareOKResult<_TContextOverride>;\n\n/**\n * @internal\n */\nexport interface MiddlewareBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n> {\n /**\n * Create a new builder based on the current middleware builder\n */\n unstable_pipe<$ContextOverridesOut>(\n fn:\n | MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverrides,\n $ContextOverridesOut,\n TInputOut\n >\n | MiddlewareBuilder<\n Overwrite<TContext, TContextOverrides>,\n TMeta,\n $ContextOverridesOut,\n TInputOut\n >,\n ): MiddlewareBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverridesOut>,\n TInputOut\n >;\n\n /**\n * List of middlewares within this middleware builder\n */\n _middlewares: MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverrides,\n object,\n TInputOut\n >[];\n}\n\n/**\n * @internal\n */\nexport type MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverridesIn,\n $ContextOverridesOut,\n TInputOut,\n> = {\n (opts: {\n ctx: Simplify<Overwrite<TContext, TContextOverridesIn>>;\n type: ProcedureType;\n path: string;\n input: TInputOut;\n getRawInput: GetRawInputFn;\n meta: TMeta | undefined;\n signal: AbortSignal | undefined;\n /**\n * The index of this call in a batch request.\n */\n batchIndex: number;\n next: {\n (): Promise<MiddlewareResult<TContextOverridesIn>>;\n <$ContextOverride>(opts: {\n ctx?: $ContextOverride;\n input?: unknown;\n }): Promise<MiddlewareResult<$ContextOverride>>;\n (opts: {\n getRawInput: GetRawInputFn;\n }): Promise<MiddlewareResult<TContextOverridesIn>>;\n };\n }): Promise<MiddlewareResult<$ContextOverridesOut>>;\n _type?: string | undefined;\n};\n\nexport type AnyMiddlewareFunction = MiddlewareFunction<any, any, any, any, any>;\nexport type AnyMiddlewareBuilder = MiddlewareBuilder<any, any, any, any>;\n/**\n * @internal\n */\nexport function createMiddlewareFactory<\n TContext,\n TMeta,\n TInputOut = unknown,\n>() {\n function createMiddlewareInner(\n middlewares: AnyMiddlewareFunction[],\n ): AnyMiddlewareBuilder {\n return {\n _middlewares: middlewares,\n unstable_pipe(middlewareBuilderOrFn) {\n const pipedMiddleware =\n '_middlewares' in middlewareBuilderOrFn\n ? middlewareBuilderOrFn._middlewares\n : [middlewareBuilderOrFn];\n\n return createMiddlewareInner([...middlewares, ...pipedMiddleware]);\n },\n };\n }\n\n function createMiddleware<$ContextOverrides>(\n fn: MiddlewareFunction<\n TContext,\n TMeta,\n object,\n $ContextOverrides,\n TInputOut\n >,\n ): MiddlewareBuilder<TContext, TMeta, $ContextOverrides, TInputOut> {\n return createMiddlewareInner([fn]);\n }\n\n return createMiddleware;\n}\n\n/**\n * Create a standalone middleware\n * @see https://trpc.io/docs/v11/server/middlewares#experimental-standalone-middlewares\n * @deprecated use `.concat()` instead\n */\nexport const experimental_standaloneMiddleware = <\n TCtx extends {\n ctx?: object;\n meta?: object;\n input?: unknown;\n },\n>() => ({\n create: createMiddlewareFactory<\n TCtx extends { ctx: infer T extends object } ? T : any,\n TCtx extends { meta: infer T extends object } ? T : object,\n TCtx extends { input: infer T } ? T : unknown\n >(),\n});\n\n/**\n * @internal\n * Please note, `trpc-openapi` uses this function.\n */\nexport function createInputMiddleware<TInput>(parse: ParseFn<TInput>) {\n const inputMiddleware: AnyMiddlewareFunction =\n async function inputValidatorMiddleware(opts) {\n let parsedInput: ReturnType<typeof parse>;\n\n const rawInput = await opts.getRawInput();\n try {\n parsedInput = await parse(rawInput);\n } catch (cause) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n cause,\n });\n }\n\n // Multiple input parsers\n const combinedInput =\n isObject(opts.input) && isObject(parsedInput)\n ? {\n ...opts.input,\n ...parsedInput,\n }\n : parsedInput;\n\n return opts.next({ input: combinedInput });\n };\n inputMiddleware._type = 'input';\n return inputMiddleware;\n}\n\n/**\n * @internal\n */\nexport function createErrorFormatterMiddleware(\n formatter: AnyProcedureErrorFormatter,\n isDev: boolean,\n) {\n const errorMiddleware: AnyMiddlewareFunction =\n async function errorFormatterMiddleware(opts) {\n const tryFormat = (error: TRPCError): TRPCError => {\n // a handler further down the chain already claimed this error\n if (isFormattedErrorShape(error)) {\n return error;\n }\n\n const shape = formatter({\n error,\n type: opts.type,\n path: opts.path,\n input: opts.input,\n ctx: opts.ctx,\n shape: getDefaultErrorShape({\n error,\n path: opts.path,\n isDev,\n }),\n });\n\n if (shape !== undefined) {\n setFormattedErrorShape(error, shape);\n }\n\n return error;\n };\n\n const tryFormatThrown = (cause: unknown): unknown => {\n const formatted = tryFormat(getTRPCErrorFromUnknown(cause));\n\n return isFormattedErrorShape(formatted) ? formatted : cause;\n };\n\n async function* wrapIterable(iterable: AsyncIterable<unknown>) {\n try {\n return yield* iterable;\n } catch (cause) {\n throw tryFormatThrown(cause);\n }\n }\n\n function wrapObservable(source: Observable<unknown, unknown>) {\n return observable((observer) =>\n source.subscribe({\n next: (value) => observer.next(value),\n error: (cause) => observer.error(tryFormatThrown(cause)),\n complete: () => observer.complete(),\n }),\n );\n }\n\n const result = await opts.next();\n\n // normal procedures return errors immediately\n if (!result.ok) {\n tryFormat(result.error);\n return result;\n }\n\n // subscription/streaming procedures need to be enumerated to find errors\n if (isAsyncIterable(result.data)) {\n return { ...result, data: wrapIterable(result.data) };\n }\n if (opts.type === 'subscription' && isObservable(result.data)) {\n return { ...result, data: wrapObservable(result.data) };\n }\n\n return result;\n };\n\n errorMiddleware._type = 'errors';\n\n return errorMiddleware;\n}\n\n/**\n * @internal\n */\nexport function createOutputMiddleware<TOutput>(parse: ParseFn<TOutput>) {\n const outputMiddleware: AnyMiddlewareFunction =\n async function outputValidatorMiddleware({ next }) {\n const result = await next();\n if (!result.ok) {\n // pass through failures without validating\n return result;\n }\n try {\n const data = await parse(result.data);\n return {\n ...result,\n data,\n };\n } catch (cause) {\n throw new TRPCError({\n message: 'Output validation failed',\n code: 'INTERNAL_SERVER_ERROR',\n cause,\n });\n }\n };\n outputMiddleware._type = 'output';\n return outputMiddleware;\n}\n","import type { StandardSchemaV1 } from \"./spec\";\n\n/** A schema error with useful information. */\n\nexport class StandardSchemaV1Error extends Error {\n /** The schema issues. */\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;\n\n /**\n * Creates a schema error with useful information.\n *\n * @param issues The schema issues.\n */\n constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n super(issues[0]?.message);\n this.name = 'SchemaError';\n this.issues = issues;\n }\n}\n","import { StandardSchemaV1Error } from '../vendor/standard-schema-v1/error';\nimport { type StandardSchemaV1 } from '../vendor/standard-schema-v1/spec';\n\n// zod / typeschema\nexport type ParserZodEsque<TInput, TParsedInput> = {\n _input: TInput;\n _output: TParsedInput;\n};\n\nexport type ParserValibotEsque<TInput, TParsedInput> = {\n schema: {\n _types?: {\n input: TInput;\n output: TParsedInput;\n };\n };\n};\n\nexport type ParserArkTypeEsque<TInput, TParsedInput> = {\n inferIn: TInput;\n infer: TParsedInput;\n};\n\nexport type ParserStandardSchemaEsque<TInput, TParsedInput> = StandardSchemaV1<\n TInput,\n TParsedInput\n>;\n\nexport type ParserMyZodEsque<TInput> = {\n parse: (input: any) => TInput;\n};\n\nexport type ParserSuperstructEsque<TInput> = {\n create: (input: unknown) => TInput;\n};\n\nexport type ParserCustomValidatorEsque<TInput> = (\n input: unknown,\n) => Promise<TInput> | TInput;\n\nexport type ParserYupEsque<TInput> = {\n validateSync: (input: unknown) => TInput;\n};\n\nexport type ParserScaleEsque<TInput> = {\n assert(value: unknown): asserts value is TInput;\n};\n\nexport type ParserWithoutInput<TInput> =\n | ParserCustomValidatorEsque<TInput>\n | ParserMyZodEsque<TInput>\n | ParserScaleEsque<TInput>\n | ParserSuperstructEsque<TInput>\n | ParserYupEsque<TInput>;\n\nexport type ParserWithInputOutput<TInput, TParsedInput> =\n | ParserZodEsque<TInput, TParsedInput>\n | ParserValibotEsque<TInput, TParsedInput>\n | ParserArkTypeEsque<TInput, TParsedInput>\n | ParserStandardSchemaEsque<TInput, TParsedInput>;\n\nexport type Parser = ParserWithInputOutput<any, any> | ParserWithoutInput<any>;\n\nexport type inferParser<TParser extends Parser> =\n TParser extends ParserStandardSchemaEsque<infer $TIn, infer $TOut>\n ? {\n in: $TIn;\n out: $TOut;\n }\n : TParser extends ParserWithInputOutput<infer $TIn, infer $TOut>\n ? {\n in: $TIn;\n out: $TOut;\n }\n : TParser extends ParserWithoutInput<infer $InOut>\n ? {\n in: $InOut;\n out: $InOut;\n }\n : never;\n\nexport type ParseFn<TType> = (value: unknown) => Promise<TType> | TType;\n\nexport function getParseFn<TType>(procedureParser: Parser): ParseFn<TType> {\n const parser = procedureParser as any;\n const isStandardSchema = '~standard' in parser;\n\n if (typeof parser === 'function' && typeof parser.assert === 'function') {\n // ParserArkTypeEsque - arktype schemas shouldn't be called as a function because they return a union type instead of throwing\n return parser.assert.bind(parser);\n }\n\n if (typeof parser === 'function' && !isStandardSchema) {\n // ParserValibotEsque (>= v0.31.0)\n // ParserCustomValidatorEsque - note the check for standard-schema conformance - some libraries like `effect` use function schemas which are *not* a \"parse\" function.\n return parser;\n }\n\n if (typeof parser.parseAsync === 'function') {\n // ParserZodEsque\n return parser.parseAsync.bind(parser);\n }\n\n if (typeof parser.parse === 'function') {\n // ParserZodEsque\n // ParserValibotEsque (< v0.13.0)\n return parser.parse.bind(parser);\n }\n\n if (typeof parser.validateSync === 'function') {\n // ParserYupEsque\n return parser.validateSync.bind(parser);\n }\n\n if (typeof parser.create === 'function') {\n // ParserSuperstructEsque\n return parser.create.bind(parser);\n }\n\n if (typeof parser.assert === 'function') {\n // ParserScaleEsque\n return (value) => {\n parser.assert(value);\n return value as TType;\n };\n }\n\n if (isStandardSchema) {\n // StandardSchemaEsque\n return async (value) => {\n const result = await parser['~standard'].validate(value);\n if (result.issues) {\n throw new StandardSchemaV1Error(result.issues);\n }\n return result.value;\n };\n }\n\n throw new Error('Could not find a validator fn');\n}\n","import type { CombinedDataTransformer } from '../unstable-core-do-not-import';\nimport type { DefaultErrorShape, ErrorFormatter } from './error/formatter';\nimport type { JSONLProducerOptions } from './stream/jsonl';\nimport type { SSEStreamProducerOptions } from './stream/sse';\n\n/**\n * The initial generics that are used in the init function\n * @internal\n */\nexport interface RootTypes {\n ctx: object;\n meta: object;\n errorShape: DefaultErrorShape;\n transformer: boolean;\n}\n\n/**\n * Recommended content types for batch stream responses.\n *\n * `application/json` remains the default for backwards compatibility, while\n * other string values are allowed for tooling or infrastructure compatibility.\n */\nexport type JSONLContentType =\n | 'application/json'\n | 'application/jsonl'\n | 'application/x-ndjson'\n | (string & {});\n\nexport interface JSONLConfig extends Pick<JSONLProducerOptions, 'pingMs'> {\n /**\n * The `content-type` header to use for batch stream responses.\n * Supports any valid content type string.\n * Defaults to `application/json` for backwards compatibility.\n * @default 'application/json'\n */\n contentType?: JSONLContentType;\n}\n\n/**\n * The default check to see if we're in a server\n */\nexport const isServerDefault: boolean =\n typeof window === 'undefined' ||\n 'Deno' in window ||\n // eslint-disable-next-line @typescript-eslint/dot-notation\n globalThis.process?.env?.['NODE_ENV'] === 'test' ||\n !!globalThis.process?.env?.['JEST_WORKER_ID'] ||\n !!globalThis.process?.env?.['VITEST_WORKER_ID'];\n\n/**\n * The default check to see if we're in development\n */\nexport function isDevDefault(): boolean {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n return globalThis.process?.env['NODE_ENV'] !== 'production';\n}\n\n/**\n * The tRPC root config\n * @internal\n */\nexport interface RootConfig<TTypes extends RootTypes> {\n /**\n * The types that are used in the config\n * @internal\n */\n $types: TTypes;\n /**\n * Use a data transformer\n * @see https://trpc.io/docs/v11/data-transformers\n */\n transformer: CombinedDataTransformer;\n /**\n * Use custom error formatting\n * @see https://trpc.io/docs/v11/error-formatting\n */\n errorFormatter: ErrorFormatter<TTypes['ctx'], TTypes['errorShape']>;\n /**\n * Allow `@trpc/server` to run in non-server environments\n * @warning **Use with caution**, this should likely mainly be used within testing.\n * @default false\n */\n allowOutsideOfServer: boolean;\n /**\n * Is this a server environment?\n * @warning **Use with caution**, this should likely mainly be used within testing.\n * @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'\n */\n isServer: boolean;\n /**\n * Is this development?\n * Will be used to decide if the API should return stack traces\n * @default process.env.NODE_ENV !== 'production'\n */\n isDev: boolean;\n\n defaultMeta?: TTypes['meta'] extends object ? TTypes['meta'] : never;\n\n /**\n * Options for server-sent events (SSE) subscriptions\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\n sse?: {\n /**\n * Enable server-sent events (SSE) subscriptions\n * @default true\n */\n enabled?: boolean;\n } & Pick<\n SSEStreamProducerOptions,\n 'ping' | 'emitAndEndImmediately' | 'maxDurationMs' | 'client'\n >;\n\n /**\n * Options for batch stream\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\n jsonl?: JSONLConfig;\n experimental?: {};\n}\n\n/**\n * @internal\n */\nexport type CreateRootTypes<TGenerics extends RootTypes> = TGenerics;\n\nexport type AnyRootTypes = CreateRootTypes<{\n ctx: any;\n meta: any;\n errorShape: any;\n transformer: any;\n}>;\n\ntype PartialIf<TCondition extends boolean, TType> = TCondition extends true\n ? Partial<TType>\n : TType;\n\n/**\n * Adds a `createContext` option with a given callback function\n * If context is the default value, then the `createContext` option is optional\n */\nexport type CreateContextCallback<\n TContext,\n TFunction extends (...args: any[]) => any,\n> = PartialIf<\n object extends TContext ? true : false,\n {\n /**\n * @see https://trpc.io/docs/v11/context\n **/\n createContext: TFunction;\n }\n>;\n","import type { inferObservableValue, Observable } from '../observable';\nimport type { ProcedureErrorFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n AnyMiddlewareFunction,\n MiddlewareBuilder,\n MiddlewareFunction,\n MiddlewareResult,\n} from './middleware';\nimport {\n createErrorFormatterMiddleware,\n createInputMiddleware,\n createOutputMiddleware,\n middlewareMarker,\n} from './middleware';\nimport type { inferParser, Parser } from './parser';\nimport { getParseFn } from './parser';\nimport type {\n AnyMutationProcedure,\n AnyProcedure,\n AnyQueryProcedure,\n LegacyObservableSubscriptionProcedure,\n MutationProcedure,\n ProcedureType,\n QueryProcedure,\n SubscriptionProcedure,\n} from './procedure';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { isDevDefault } from './rootConfig';\nimport type { TRPCErrorShape } from './rpc';\nimport type { inferTrackedOutput } from './stream/tracked';\nimport type {\n GetRawInputFn,\n MaybePromise,\n Overwrite,\n Simplify,\n TypeError,\n} from './types';\nimport type { UnsetMarker } from './utils';\nimport { mergeWithoutOverrides } from './utils';\n\ntype IntersectIfDefined<TType, TWith> = TType extends UnsetMarker\n ? TWith\n : TWith extends UnsetMarker\n ? TType\n : Simplify<TType & TWith>;\n\ntype DefaultValue<TValue, TFallback> = TValue extends UnsetMarker\n ? TFallback\n : TValue;\n\ntype FoldErrorShape<TErrorShape, $Shape> =\n Extract<$Shape, TRPCErrorShape> | TErrorShape;\n\ntype inferAsyncIterable<TOutput> =\n TOutput extends AsyncIterable<infer $Yield, infer $Return, infer $Next>\n ? {\n yield: $Yield;\n return: $Return;\n next: $Next;\n }\n : never;\ntype inferSubscriptionOutput<TOutput> =\n TOutput extends AsyncIterable<any>\n ? AsyncIterable<\n inferTrackedOutput<inferAsyncIterable<TOutput>['yield']>,\n inferAsyncIterable<TOutput>['return'],\n inferAsyncIterable<TOutput>['next']\n >\n : TypeError<'Subscription output could not be inferred'>;\n\nexport type CallerOverride<TContext> = (opts: {\n args: unknown[];\n invoke: (opts: ProcedureCallOptions<TContext>) => Promise<unknown>;\n _def: AnyProcedure['_def'];\n}) => Promise<unknown>;\ntype ProcedureBuilderDef<TMeta> = {\n procedure: true;\n inputs: Parser[];\n output?: Parser;\n meta?: TMeta;\n resolver?: ProcedureBuilderResolver;\n middlewares: AnyMiddlewareFunction[];\n /**\n * @deprecated use `type` instead\n */\n mutation?: boolean;\n /**\n * @deprecated use `type` instead\n */\n query?: boolean;\n /**\n * @deprecated use `type` instead\n */\n subscription?: boolean;\n type?: ProcedureType;\n caller?: CallerOverride<unknown>;\n config?: RootConfig<AnyRootTypes>;\n};\n\ntype AnyProcedureBuilderDef = ProcedureBuilderDef<any>;\n\n/**\n * Procedure resolver options (what the `.query()`, `.mutation()`, and `.subscription()` functions receive)\n * @internal\n */\nexport interface ProcedureResolverOptions<\n TContext,\n _TMeta,\n TContextOverridesIn,\n TInputOut,\n> {\n ctx: Simplify<Overwrite<TContext, TContextOverridesIn>>;\n input: TInputOut extends UnsetMarker ? undefined : TInputOut;\n /**\n * The AbortSignal of the request\n */\n signal: AbortSignal | undefined;\n /**\n * The path of the procedure\n */\n path: string;\n /**\n * The index of this call in a batch request.\n * Will be set when the procedure is called as part of a batch.\n */\n batchIndex?: number;\n}\n\n/**\n * A procedure resolver\n */\ntype ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputParserIn,\n $Output,\n> = (\n opts: ProcedureResolverOptions<TContext, TMeta, TContextOverrides, TInputOut>,\n) => MaybePromise<\n // If an output parser is defined, we need to return what the parser expects, otherwise we return the inferred type\n DefaultValue<TOutputParserIn, $Output>\n>;\n\ntype AnyResolver = ProcedureResolver<any, any, any, any, any, any>;\nexport type AnyProcedureBuilder = ProcedureBuilder<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n/**\n * Infer the context type from a procedure builder\n * Useful to create common helper functions for different procedures\n */\nexport type inferProcedureBuilderResolverOptions<\n TProcedureBuilder extends AnyProcedureBuilder,\n> =\n TProcedureBuilder extends ProcedureBuilder<\n infer TContext,\n infer TMeta,\n infer TContextOverrides,\n infer _TInputIn,\n infer TInputOut,\n infer _TOutputIn,\n infer _TOutputOut,\n infer _TCaller,\n infer _TErrorShape\n >\n ? ProcedureResolverOptions<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut extends UnsetMarker\n ? // if input is not set, we don't want to infer it as `undefined` since a procedure further down the chain might have set an input\n unknown\n : TInputOut extends object\n ? Simplify<\n TInputOut & {\n /**\n * Extra input params might have been added by a `.input()` further down the chain\n */\n [keyAddedByInputCallFurtherDown: string]: unknown;\n }\n >\n : TInputOut\n >\n : never;\n\nexport interface ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller extends boolean,\n /**\n * Defaults to `unknown` so that an annotation written without it falls back\n * to the router-wide error shape rather than pinning the procedure to the\n * default one.\n * @see inferProcedureErrorShape\n */\n TErrorShape = unknown,\n> {\n /**\n * Add an input parser to the procedure.\n * @see https://trpc.io/docs/v11/server/validators\n */\n input<$Parser extends Parser>(\n schema: TInputOut extends UnsetMarker\n ? $Parser\n : inferParser<$Parser>['out'] extends Record<string, unknown> | undefined\n ? TInputOut extends Record<string, unknown> | undefined\n ? undefined extends inferParser<$Parser>['out'] // if current is optional the previous must be too\n ? undefined extends TInputOut\n ? $Parser\n : TypeError<'Cannot chain an optional parser to a required parser'>\n : $Parser\n : TypeError<'All input parsers did not resolve to an object'>\n : TypeError<'All input parsers did not resolve to an object'>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n IntersectIfDefined<TInputIn, inferParser<$Parser>['in']>,\n IntersectIfDefined<TInputOut, inferParser<$Parser>['out']>,\n TOutputIn,\n TOutputOut,\n TCaller,\n TErrorShape\n >;\n /**\n * Add an output parser to the procedure.\n * @see https://trpc.io/docs/v11/server/validators\n */\n output<$Parser extends Parser>(\n schema: $Parser,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n IntersectIfDefined<TOutputIn, inferParser<$Parser>['in']>,\n IntersectIfDefined<TOutputOut, inferParser<$Parser>['out']>,\n TCaller,\n TErrorShape\n >;\n /**\n * Add a meta data to the procedure.\n * @see https://trpc.io/docs/v11/server/metadata\n */\n meta(\n meta: TMeta,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller,\n TErrorShape\n >;\n /**\n * Add per procedure error formatters.\n *\n * An error will bubble until a `.errors()` handler returns a shape\n * or it reaches the global errorFormatter\n *\n * @see https://trpc.io/docs/v11/server/error-formatting\n */\n errors<$Shape extends TRPCErrorShape | undefined | void>(\n formatter: ProcedureErrorFormatter<TContext, TContextOverrides, $Shape>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller,\n FoldErrorShape<TErrorShape, $Shape>\n >;\n /**\n * Add a middleware to the procedure.\n * @see https://trpc.io/docs/v11/server/middlewares\n */\n use<$ContextOverridesOut>(\n fn:\n | MiddlewareBuilder<\n Overwrite<TContext, TContextOverrides>,\n TMeta,\n $ContextOverridesOut,\n TInputOut\n >\n | MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverrides,\n $ContextOverridesOut,\n TInputOut\n >,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverridesOut>,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller,\n TErrorShape\n >;\n\n /**\n * @deprecated use {@link concat} instead\n */\n unstable_concat<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n $ErrorShape,\n >(\n builder: Overwrite<TContext, TContextOverrides> extends $Context\n ? TMeta extends $Meta\n ? ProcedureBuilder<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n TCaller,\n $ErrorShape\n >\n : TypeError<'Meta mismatch'>\n : TypeError<'Context mismatch'>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverrides>,\n IntersectIfDefined<TInputIn, $InputIn>,\n IntersectIfDefined<TInputOut, $InputOut>,\n IntersectIfDefined<TOutputIn, $OutputIn>,\n IntersectIfDefined<TOutputOut, $OutputOut>,\n TCaller,\n FoldErrorShape<TErrorShape, $ErrorShape>\n >;\n\n /**\n * Combine two procedure builders\n */\n concat<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n $ErrorShape,\n >(\n builder: Overwrite<TContext, TContextOverrides> extends $Context\n ? TMeta extends $Meta\n ? ProcedureBuilder<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n TCaller,\n $ErrorShape\n >\n : TypeError<'Meta mismatch'>\n : TypeError<'Context mismatch'>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverrides>,\n IntersectIfDefined<TInputIn, $InputIn>,\n IntersectIfDefined<TInputOut, $InputOut>,\n IntersectIfDefined<TOutputIn, $OutputIn>,\n IntersectIfDefined<TOutputOut, $OutputOut>,\n TCaller,\n FoldErrorShape<TErrorShape, $ErrorShape>\n >;\n /**\n * Query procedure\n * @see https://trpc.io/docs/v11/concepts#vocabulary\n */\n query<$Output>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? (\n input: DefaultValue<TInputIn, void>,\n ) => Promise<DefaultValue<TOutputOut, $Output>>\n : QueryProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: DefaultValue<TOutputOut, $Output>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n\n /**\n * Mutation procedure\n * @see https://trpc.io/docs/v11/concepts#vocabulary\n */\n mutation<$Output>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? (\n input: DefaultValue<TInputIn, void>,\n ) => Promise<DefaultValue<TOutputOut, $Output>>\n : MutationProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: DefaultValue<TOutputOut, $Output>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n\n /**\n * Subscription procedure\n * @see https://trpc.io/docs/v11/server/subscriptions\n */\n subscription<$Output extends AsyncIterable<any, void, any>>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? TypeError<'Not implemented'>\n : SubscriptionProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: inferSubscriptionOutput<DefaultValue<TOutputOut, $Output>>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n /**\n * @deprecated Using subscriptions with an observable is deprecated. Use an async generator instead.\n * This feature will be removed in v12 of tRPC.\n * @see https://trpc.io/docs/v11/server/subscriptions\n */\n subscription<$Output extends Observable<any, any>>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? TypeError<'Not implemented'>\n : LegacyObservableSubscriptionProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: inferObservableValue<DefaultValue<TOutputOut, $Output>>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n /**\n * Overrides the way a procedure is invoked\n * Do not use this unless you know what you're doing - this is an experimental API\n */\n experimental_caller(\n caller: CallerOverride<TContext>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n true,\n TErrorShape\n >;\n /**\n * @internal\n */\n _def: ProcedureBuilderDef<TMeta>;\n}\n\ntype ProcedureBuilderResolver = (\n opts: ProcedureResolverOptions<any, any, any, any>,\n) => Promise<unknown>;\n\nfunction createNewBuilder(\n def1: AnyProcedureBuilderDef,\n def2: Partial<AnyProcedureBuilderDef>,\n): AnyProcedureBuilder {\n const { middlewares = [], inputs, meta, config, ...rest } = def2;\n\n // TODO: maybe have a fn here to warn about calls\n return createBuilder({\n ...mergeWithoutOverrides(def1, rest),\n config: def1.config ?? config,\n inputs: [...def1.inputs, ...(inputs ?? [])],\n middlewares: [...def1.middlewares, ...middlewares],\n meta: def1.meta && meta ? { ...def1.meta, ...meta } : (meta ?? def1.meta),\n });\n}\n\nexport function createBuilder<TContext, TMeta, TErrorShape = unknown>(\n initDef: Partial<AnyProcedureBuilderDef> = {},\n): ProcedureBuilder<\n TContext,\n TMeta,\n object,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n false,\n TErrorShape\n> {\n const _def: AnyProcedureBuilderDef = {\n procedure: true,\n inputs: [],\n middlewares: [],\n ...initDef,\n };\n\n const builder: AnyProcedureBuilder = {\n _def,\n input(input) {\n const parser = getParseFn(input as Parser);\n return createNewBuilder(_def, {\n inputs: [input as Parser],\n middlewares: [createInputMiddleware(parser)],\n });\n },\n output(output: Parser) {\n const parser = getParseFn(output);\n return createNewBuilder(_def, {\n output,\n middlewares: [createOutputMiddleware(parser)],\n });\n },\n meta(meta) {\n return createNewBuilder(_def, {\n meta,\n });\n },\n errors(formatter) {\n return createNewBuilder(_def, {\n middlewares: [\n createErrorFormatterMiddleware(\n formatter,\n _def.config?.isDev ?? isDevDefault(),\n ),\n ],\n });\n },\n use(middlewareBuilderOrFn) {\n // Distinguish between a middleware builder and a middleware function\n const middlewares =\n '_middlewares' in middlewareBuilderOrFn\n ? middlewareBuilderOrFn._middlewares\n : [middlewareBuilderOrFn];\n\n return createNewBuilder(_def, {\n middlewares: middlewares,\n });\n },\n unstable_concat(builder) {\n return createNewBuilder(_def, (builder as AnyProcedureBuilder)._def);\n },\n concat(builder) {\n return createNewBuilder(_def, (builder as AnyProcedureBuilder)._def);\n },\n query(resolver) {\n return createResolver(\n { ..._def, type: 'query' },\n resolver,\n ) as AnyQueryProcedure;\n },\n mutation(resolver) {\n return createResolver(\n { ..._def, type: 'mutation' },\n resolver,\n ) as AnyMutationProcedure;\n },\n subscription(resolver: ProcedureResolver<any, any, any, any, any, any>) {\n return createResolver({ ..._def, type: 'subscription' }, resolver) as any;\n },\n experimental_caller(caller) {\n return createNewBuilder(_def, {\n caller,\n }) as any;\n },\n };\n\n return builder;\n}\n\nfunction createResolver(\n _defIn: AnyProcedureBuilderDef & { type: ProcedureType },\n resolver: AnyResolver,\n) {\n const finalBuilder = createNewBuilder(_defIn, {\n resolver,\n middlewares: [\n async function resolveMiddleware(opts) {\n const data = await resolver(opts);\n return {\n marker: middlewareMarker,\n ok: true,\n data,\n ctx: opts.ctx,\n } as const;\n },\n ],\n });\n const _def: AnyProcedure['_def'] = {\n ...finalBuilder._def,\n type: _defIn.type,\n experimental_caller: Boolean(finalBuilder._def.caller),\n meta: finalBuilder._def.meta,\n $types: null as any,\n };\n\n const invoke = createProcedureCaller(finalBuilder._def);\n const callerOverride = finalBuilder._def.caller;\n if (!callerOverride) {\n return invoke;\n }\n const callerWrapper = async (...args: unknown[]) => {\n return await callerOverride({\n args,\n invoke,\n _def: _def,\n });\n };\n\n callerWrapper._def = _def;\n\n return callerWrapper;\n}\n\n/**\n * @internal\n */\nexport interface ProcedureCallOptions<TContext> {\n ctx: TContext;\n getRawInput: GetRawInputFn;\n input?: unknown;\n path: string;\n type: ProcedureType;\n signal: AbortSignal | undefined;\n /**\n * The index of this call in a batch request.\n */\n batchIndex: number;\n}\n\nconst codeblock = `\nThis is a client-only function.\nIf you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls\n`.trim();\n\n// run the middlewares recursively with the resolver as the last one\nasync function callRecursive(\n index: number,\n _def: AnyProcedureBuilderDef,\n opts: ProcedureCallOptions<any>,\n): Promise<MiddlewareResult<any>> {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const middleware = _def.middlewares[index]!;\n const result = await middleware({\n ...opts,\n meta: _def.meta,\n input: opts.input,\n next(_nextOpts?: any) {\n const nextOpts = _nextOpts as\n | {\n ctx?: Record<string, unknown>;\n input?: unknown;\n getRawInput?: GetRawInputFn;\n }\n | undefined;\n\n return callRecursive(index + 1, _def, {\n ...opts,\n ctx: nextOpts?.ctx ? { ...opts.ctx, ...nextOpts.ctx } : opts.ctx,\n input: nextOpts && 'input' in nextOpts ? nextOpts.input : opts.input,\n getRawInput: nextOpts?.getRawInput ?? opts.getRawInput,\n });\n },\n });\n\n return result;\n } catch (cause) {\n return {\n ok: false,\n error: getTRPCErrorFromUnknown(cause),\n marker: middlewareMarker,\n };\n }\n}\n\nfunction createProcedureCaller(_def: AnyProcedureBuilderDef): AnyProcedure {\n async function procedure(opts: ProcedureCallOptions<unknown>) {\n // is direct server-side call\n if (!opts || !('getRawInput' in opts)) {\n throw new Error(codeblock);\n }\n\n // there's always at least one \"next\" since we wrap this.resolver in a middleware\n const result = await callRecursive(0, _def, opts);\n\n if (!result) {\n throw new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n message:\n 'No result from middlewares - did you forget to `return next()`?',\n });\n }\n if (!result.ok) {\n // re-throw original error\n throw result.error;\n }\n return result.data;\n }\n\n procedure._def = _def;\n procedure.procedure = true;\n procedure.meta = _def.meta;\n\n // FIXME typecast shouldn't be needed - fixittt\n return procedure as unknown as AnyProcedure;\n}\n","import {\n defaultFormatter,\n type DefaultErrorShape,\n type ErrorFormatter,\n} from './error/formatter';\nimport type { MiddlewareBuilder, MiddlewareFunction } from './middleware';\nimport { createMiddlewareFactory } from './middleware';\nimport type { ProcedureBuilder } from './procedureBuilder';\nimport { createBuilder } from './procedureBuilder';\nimport type { AnyRootTypes, CreateRootTypes } from './rootConfig';\nimport { isDevDefault, isServerDefault, type RootConfig } from './rootConfig';\nimport type {\n AnyRouter,\n MergeRouters,\n RouterBuilder,\n RouterCallerFactory,\n} from './router';\nimport {\n createCallerFactory,\n createRouterFactory,\n mergeRouters,\n} from './router';\nimport type { DataTransformerOptions } from './transformer';\nimport { defaultTransformer, getDataTransformer } from './transformer';\nimport type { Unwrap, ValidateShape } from './types';\nimport type { UnsetMarker } from './utils';\n\ntype inferErrorFormatterShape<TType> =\n TType extends ErrorFormatter<any, infer TShape> ? TShape : DefaultErrorShape;\n/** @internal */\nexport interface RuntimeConfigOptions<\n TContext extends object,\n TMeta extends object,\n> extends Partial<\n Omit<\n RootConfig<{\n ctx: TContext;\n meta: TMeta;\n errorShape: any;\n transformer: any;\n }>,\n '$types' | 'transformer'\n >\n> {\n /**\n * Use a data transformer\n * @see https://trpc.io/docs/v11/data-transformers\n */\n transformer?: DataTransformerOptions;\n}\n\ntype ContextCallback = (...args: any[]) => object | Promise<object>;\n\nexport interface TRPCRootObject<\n TContext extends object,\n TMeta extends object,\n TOptions extends RuntimeConfigOptions<TContext, TMeta>,\n $Root extends AnyRootTypes = {\n ctx: TContext;\n meta: TMeta;\n errorShape: undefined extends TOptions['errorFormatter']\n ? DefaultErrorShape\n : inferErrorFormatterShape<TOptions['errorFormatter']>;\n transformer: undefined extends TOptions['transformer'] ? false : true;\n },\n> {\n /**\n * Your router config\n * @internal\n */\n _config: RootConfig<$Root>;\n\n /**\n * Builder object for creating procedures\n * @see https://trpc.io/docs/v11/server/procedures\n */\n procedure: ProcedureBuilder<\n TContext,\n TMeta,\n object,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n false,\n $Root['errorShape']\n >;\n\n /**\n * Create reusable middlewares\n * @see https://trpc.io/docs/v11/server/middlewares\n */\n middleware: <$ContextOverrides>(\n fn: MiddlewareFunction<TContext, TMeta, object, $ContextOverrides, unknown>,\n ) => MiddlewareBuilder<TContext, TMeta, $ContextOverrides, unknown>;\n\n /**\n * Create a router\n * @see https://trpc.io/docs/v11/server/routers\n */\n router: RouterBuilder<$Root>;\n\n /**\n * Merge Routers\n * @see https://trpc.io/docs/v11/server/merging-routers\n */\n mergeRouters: <TRouters extends AnyRouter[]>(\n ...routerList: [...TRouters]\n ) => MergeRouters<TRouters>;\n\n /**\n * Create a server-side caller for a router\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCallerFactory: RouterCallerFactory<$Root>;\n}\n\nclass TRPCBuilder<TContext extends object, TMeta extends object> {\n /**\n * Add a context shape as a generic to the root object\n * @see https://trpc.io/docs/v11/server/context\n */\n context<TNewContext extends object | ContextCallback>() {\n return new TRPCBuilder<\n TNewContext extends ContextCallback ? Unwrap<TNewContext> : TNewContext,\n TMeta\n >();\n }\n\n /**\n * Add a meta shape as a generic to the root object\n * @see https://trpc.io/docs/v11/quickstart\n */\n meta<TNewMeta extends object>() {\n return new TRPCBuilder<TContext, TNewMeta>();\n }\n\n /**\n * Create the root object\n * @see https://trpc.io/docs/v11/server/routers#initialize-trpc\n */\n create<TOptions extends RuntimeConfigOptions<TContext, TMeta>>(\n opts?: ValidateShape<TOptions, RuntimeConfigOptions<TContext, TMeta>>,\n ): TRPCRootObject<TContext, TMeta, TOptions> {\n type $Root = CreateRootTypes<{\n ctx: TContext;\n meta: TMeta;\n errorShape: undefined extends TOptions['errorFormatter']\n ? DefaultErrorShape\n : inferErrorFormatterShape<TOptions['errorFormatter']>;\n transformer: undefined extends TOptions['transformer'] ? false : true;\n }>;\n\n const config: RootConfig<$Root> = {\n ...opts,\n transformer: getDataTransformer(opts?.transformer ?? defaultTransformer),\n isDev: opts?.isDev ?? isDevDefault(),\n allowOutsideOfServer: opts?.allowOutsideOfServer ?? false,\n errorFormatter: opts?.errorFormatter ?? defaultFormatter,\n isServer: opts?.isServer ?? isServerDefault,\n /**\n * These are just types, they can't be used at runtime\n * @internal\n */\n $types: null as any,\n };\n\n {\n // Server check\n const isServer: boolean = opts?.isServer ?? isServerDefault;\n\n if (!isServer && opts?.allowOutsideOfServer !== true) {\n throw new Error(\n `You're trying to use @trpc/server in a non-server environment. This is not supported by default.`,\n );\n }\n }\n return {\n /**\n * Your router config\n * @internal\n */\n _config: config,\n /**\n * Builder object for creating procedures\n * @see https://trpc.io/docs/v11/server/procedures\n */\n procedure: createBuilder<\n $Root['ctx'],\n $Root['meta'],\n $Root['errorShape']\n >({\n meta: opts?.defaultMeta,\n config,\n }),\n /**\n * Create reusable middlewares\n * @see https://trpc.io/docs/v11/server/middlewares\n */\n middleware: createMiddlewareFactory<$Root['ctx'], $Root['meta']>(),\n /**\n * Create a router\n * @see https://trpc.io/docs/v11/server/routers\n */\n router: createRouterFactory<$Root>(config),\n /**\n * Merge Routers\n * @see https://trpc.io/docs/v11/server/merging-routers\n */\n mergeRouters,\n /**\n * Create a server-side caller for a router\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCallerFactory: createCallerFactory<$Root>(),\n };\n }\n}\n\n/**\n * Builder to initialize the tRPC root object - use this exactly once per backend\n * @see https://trpc.io/docs/v11/quickstart\n */\nexport const initTRPC = new TRPCBuilder();\nexport type { TRPCBuilder };\n"],"mappings":";;;;;;AAeA,MAAa,mBAAmB;;;;AAwHhC,SAAgB,0BAIZ;CACF,SAAS,sBACP,aACsB;EACtB,OAAO;GACL,cAAc;GACd,cAAc,uBAAuB;IACnC,MAAM,kBACJ,kBAAkB,wBACd,sBAAsB,eACtB,CAAC,qBAAqB;IAE5B,OAAO,sBAAsB,CAAC,GAAG,aAAa,GAAG,eAAe,CAAC;GACnE;EACF;CACF;CAEA,SAAS,iBACP,IAOkE;EAClE,OAAO,sBAAsB,CAAC,EAAE,CAAC;CACnC;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,2CAML,EACN,QAAQ,wBAIN,EACJ;;;;;AAMA,SAAgB,sBAA8B,OAAwB;CACpE,MAAM,kBACJ,eAAe,yBAAyB,MAAM;EAC5C,IAAI;EAEJ,MAAM,WAAW,MAAM,KAAK,YAAY;EACxC,IAAI;GACF,cAAc,MAAM,MAAM,QAAQ;EACpC,SAAS,OAAO;GACd,MAAM,IAAI,UAAU;IAClB,MAAM;IACN;GACF,CAAC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ClD;CACF;AACF,EAMwC"}
|
|
1
|
+
{"version":3,"file":"initTRPC-RMeQIy9H.mjs","names":[],"sources":["../src/unstable-core-do-not-import/middleware.ts","../src/vendor/standard-schema-v1/error.ts","../src/unstable-core-do-not-import/parser.ts","../src/unstable-core-do-not-import/rootConfig.ts","../src/unstable-core-do-not-import/procedureBuilder.ts","../src/unstable-core-do-not-import/initTRPC.ts"],"sourcesContent":["import type { Observable } from '../observable';\nimport { isObservable, observable } from '../observable';\nimport type { AnyProcedureErrorFormatter } from './error/formatter';\nimport {\n getDefaultErrorShape,\n isFormattedErrorShape,\n setFormattedErrorShape,\n} from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type { ParseFn } from './parser';\nimport type { ProcedureType } from './procedure';\nimport type { GetRawInputFn, Overwrite, Simplify } from './types';\nimport { isAsyncIterable, isObject } from './utils';\n\n/** @internal */\nexport const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {\n __brand: 'middlewareMarker';\n};\ntype MiddlewareMarker = typeof middlewareMarker;\n\ninterface MiddlewareResultBase {\n /**\n * All middlewares should pass through their `next()`'s output.\n * Requiring this marker makes sure that can't be forgotten at compile-time.\n */\n readonly marker: MiddlewareMarker;\n}\n\ninterface MiddlewareOKResult<_TContextOverride> extends MiddlewareResultBase {\n ok: true;\n data: unknown;\n // this could be extended with `input`/`rawInput` later\n}\n\ninterface MiddlewareErrorResult<\n _TContextOverride,\n> extends MiddlewareResultBase {\n ok: false;\n error: TRPCError;\n}\n\n/**\n * @internal\n */\nexport type MiddlewareResult<_TContextOverride> =\n | MiddlewareErrorResult<_TContextOverride>\n | MiddlewareOKResult<_TContextOverride>;\n\n/**\n * @internal\n */\nexport interface MiddlewareBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n> {\n /**\n * Create a new builder based on the current middleware builder\n */\n unstable_pipe<$ContextOverridesOut>(\n fn:\n | MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverrides,\n $ContextOverridesOut,\n TInputOut\n >\n | MiddlewareBuilder<\n Overwrite<TContext, TContextOverrides>,\n TMeta,\n $ContextOverridesOut,\n TInputOut\n >,\n ): MiddlewareBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverridesOut>,\n TInputOut\n >;\n\n /**\n * List of middlewares within this middleware builder\n */\n _middlewares: MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverrides,\n object,\n TInputOut\n >[];\n}\n\n/**\n * @internal\n */\nexport type MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverridesIn,\n $ContextOverridesOut,\n TInputOut,\n> = {\n (opts: {\n ctx: Simplify<Overwrite<TContext, TContextOverridesIn>>;\n type: ProcedureType;\n path: string;\n input: TInputOut;\n getRawInput: GetRawInputFn;\n meta: TMeta | undefined;\n signal: AbortSignal | undefined;\n /**\n * The index of this call in a batch request.\n */\n batchIndex: number;\n next: {\n (): Promise<MiddlewareResult<TContextOverridesIn>>;\n <$ContextOverride>(opts: {\n ctx?: $ContextOverride;\n input?: unknown;\n }): Promise<MiddlewareResult<$ContextOverride>>;\n (opts: {\n getRawInput: GetRawInputFn;\n }): Promise<MiddlewareResult<TContextOverridesIn>>;\n };\n }): Promise<MiddlewareResult<$ContextOverridesOut>>;\n _type?: string | undefined;\n};\n\nexport type AnyMiddlewareFunction = MiddlewareFunction<any, any, any, any, any>;\nexport type AnyMiddlewareBuilder = MiddlewareBuilder<any, any, any, any>;\n/**\n * @internal\n */\nexport function createMiddlewareFactory<\n TContext,\n TMeta,\n TInputOut = unknown,\n>() {\n function createMiddlewareInner(\n middlewares: AnyMiddlewareFunction[],\n ): AnyMiddlewareBuilder {\n return {\n _middlewares: middlewares,\n unstable_pipe(middlewareBuilderOrFn) {\n const pipedMiddleware =\n '_middlewares' in middlewareBuilderOrFn\n ? middlewareBuilderOrFn._middlewares\n : [middlewareBuilderOrFn];\n\n return createMiddlewareInner([...middlewares, ...pipedMiddleware]);\n },\n };\n }\n\n function createMiddleware<$ContextOverrides>(\n fn: MiddlewareFunction<\n TContext,\n TMeta,\n object,\n $ContextOverrides,\n TInputOut\n >,\n ): MiddlewareBuilder<TContext, TMeta, $ContextOverrides, TInputOut> {\n return createMiddlewareInner([fn]);\n }\n\n return createMiddleware;\n}\n\n/**\n * Create a standalone middleware\n * @see https://trpc.io/docs/v11/server/middlewares#experimental-standalone-middlewares\n * @deprecated use `.concat()` instead\n */\nexport const experimental_standaloneMiddleware = <\n TCtx extends {\n ctx?: object;\n meta?: object;\n input?: unknown;\n },\n>() => ({\n create: createMiddlewareFactory<\n TCtx extends { ctx: infer T extends object } ? T : any,\n TCtx extends { meta: infer T extends object } ? T : object,\n TCtx extends { input: infer T } ? T : unknown\n >(),\n});\n\n/**\n * @internal\n * Please note, `trpc-openapi` uses this function.\n */\nexport function createInputMiddleware<TInput>(parse: ParseFn<TInput>) {\n const inputMiddleware: AnyMiddlewareFunction =\n async function inputValidatorMiddleware(opts) {\n let parsedInput: ReturnType<typeof parse>;\n\n const rawInput = await opts.getRawInput();\n try {\n parsedInput = await parse(rawInput);\n } catch (cause) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n cause,\n });\n }\n\n // Multiple input parsers\n const combinedInput =\n isObject(opts.input) && isObject(parsedInput)\n ? {\n ...opts.input,\n ...parsedInput,\n }\n : parsedInput;\n\n return opts.next({ input: combinedInput });\n };\n inputMiddleware._type = 'input';\n return inputMiddleware;\n}\n\n/**\n * @internal\n */\nexport function createErrorFormatterMiddleware(\n formatter: AnyProcedureErrorFormatter,\n isDev: boolean,\n) {\n const errorMiddleware: AnyMiddlewareFunction =\n async function errorFormatterMiddleware(opts) {\n const tryFormat = (error: TRPCError): TRPCError => {\n // a handler further down the chain already claimed this error\n if (isFormattedErrorShape(error)) {\n return error;\n }\n\n const shape = formatter({\n error,\n type: opts.type,\n path: opts.path,\n input: opts.input,\n ctx: opts.ctx,\n shape: getDefaultErrorShape({\n error,\n path: opts.path,\n isDev,\n }),\n });\n\n if (shape !== undefined) {\n setFormattedErrorShape(error, shape);\n }\n\n return error;\n };\n\n const tryFormatThrown = (cause: unknown): unknown => {\n const formatted = tryFormat(getTRPCErrorFromUnknown(cause));\n\n return isFormattedErrorShape(formatted) ? formatted : cause;\n };\n\n async function* wrapIterable(iterable: AsyncIterable<unknown>) {\n try {\n return yield* iterable;\n } catch (cause) {\n throw tryFormatThrown(cause);\n }\n }\n\n function wrapObservable(source: Observable<unknown, unknown>) {\n return observable((observer) =>\n source.subscribe({\n next: (value) => observer.next(value),\n error: (cause) => observer.error(tryFormatThrown(cause)),\n complete: () => observer.complete(),\n }),\n );\n }\n\n const result = await opts.next();\n\n // normal procedures return errors immediately\n if (!result.ok) {\n tryFormat(result.error);\n return result;\n }\n\n // subscription/streaming procedures need to be enumerated to find errors\n if (isAsyncIterable(result.data)) {\n return { ...result, data: wrapIterable(result.data) };\n }\n if (opts.type === 'subscription' && isObservable(result.data)) {\n return { ...result, data: wrapObservable(result.data) };\n }\n\n return result;\n };\n\n errorMiddleware._type = 'errors';\n\n return errorMiddleware;\n}\n\n/**\n * @internal\n */\nexport function createOutputMiddleware<TOutput>(parse: ParseFn<TOutput>) {\n const outputMiddleware: AnyMiddlewareFunction =\n async function outputValidatorMiddleware({ next }) {\n const result = await next();\n if (!result.ok) {\n // pass through failures without validating\n return result;\n }\n try {\n const data = await parse(result.data);\n return {\n ...result,\n data,\n };\n } catch (cause) {\n throw new TRPCError({\n message: 'Output validation failed',\n code: 'INTERNAL_SERVER_ERROR',\n cause,\n });\n }\n };\n outputMiddleware._type = 'output';\n return outputMiddleware;\n}\n","import type { StandardSchemaV1 } from \"./spec\";\n\n/** A schema error with useful information. */\n\nexport class StandardSchemaV1Error extends Error {\n /** The schema issues. */\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;\n\n /**\n * Creates a schema error with useful information.\n *\n * @param issues The schema issues.\n */\n constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n super(issues[0]?.message);\n this.name = 'SchemaError';\n this.issues = issues;\n }\n}\n","import { StandardSchemaV1Error } from '../vendor/standard-schema-v1/error';\nimport { type StandardSchemaV1 } from '../vendor/standard-schema-v1/spec';\n\n// zod / typeschema\nexport type ParserZodEsque<TInput, TParsedInput> = {\n _input: TInput;\n _output: TParsedInput;\n};\n\nexport type ParserValibotEsque<TInput, TParsedInput> = {\n schema: {\n _types?: {\n input: TInput;\n output: TParsedInput;\n };\n };\n};\n\nexport type ParserArkTypeEsque<TInput, TParsedInput> = {\n inferIn: TInput;\n infer: TParsedInput;\n};\n\nexport type ParserStandardSchemaEsque<TInput, TParsedInput> = StandardSchemaV1<\n TInput,\n TParsedInput\n>;\n\nexport type ParserMyZodEsque<TInput> = {\n parse: (input: any) => TInput;\n};\n\nexport type ParserSuperstructEsque<TInput> = {\n create: (input: unknown) => TInput;\n};\n\nexport type ParserCustomValidatorEsque<TInput> = (\n input: unknown,\n) => Promise<TInput> | TInput;\n\nexport type ParserYupEsque<TInput> = {\n validateSync: (input: unknown) => TInput;\n};\n\nexport type ParserScaleEsque<TInput> = {\n assert(value: unknown): asserts value is TInput;\n};\n\nexport type ParserWithoutInput<TInput> =\n | ParserCustomValidatorEsque<TInput>\n | ParserMyZodEsque<TInput>\n | ParserScaleEsque<TInput>\n | ParserSuperstructEsque<TInput>\n | ParserYupEsque<TInput>;\n\nexport type ParserWithInputOutput<TInput, TParsedInput> =\n | ParserZodEsque<TInput, TParsedInput>\n | ParserValibotEsque<TInput, TParsedInput>\n | ParserArkTypeEsque<TInput, TParsedInput>\n | ParserStandardSchemaEsque<TInput, TParsedInput>;\n\nexport type Parser = ParserWithInputOutput<any, any> | ParserWithoutInput<any>;\n\nexport type inferParser<TParser extends Parser> =\n TParser extends ParserStandardSchemaEsque<infer $TIn, infer $TOut>\n ? {\n in: $TIn;\n out: $TOut;\n }\n : TParser extends ParserWithInputOutput<infer $TIn, infer $TOut>\n ? {\n in: $TIn;\n out: $TOut;\n }\n : TParser extends ParserWithoutInput<infer $InOut>\n ? {\n in: $InOut;\n out: $InOut;\n }\n : never;\n\nexport type ParseFn<TType> = (value: unknown) => Promise<TType> | TType;\n\nexport function getParseFn<TType>(procedureParser: Parser): ParseFn<TType> {\n const parser = procedureParser as any;\n const isStandardSchema = '~standard' in parser;\n\n if (typeof parser === 'function' && typeof parser.assert === 'function') {\n // ParserArkTypeEsque - arktype schemas shouldn't be called as a function because they return a union type instead of throwing\n return parser.assert.bind(parser);\n }\n\n if (typeof parser === 'function' && !isStandardSchema) {\n // ParserValibotEsque (>= v0.31.0)\n // ParserCustomValidatorEsque - note the check for standard-schema conformance - some libraries like `effect` use function schemas which are *not* a \"parse\" function.\n return parser;\n }\n\n if (typeof parser.parseAsync === 'function') {\n // ParserZodEsque\n return parser.parseAsync.bind(parser);\n }\n\n if (typeof parser.parse === 'function') {\n // ParserZodEsque\n // ParserValibotEsque (< v0.13.0)\n return parser.parse.bind(parser);\n }\n\n if (typeof parser.validateSync === 'function') {\n // ParserYupEsque\n return parser.validateSync.bind(parser);\n }\n\n if (typeof parser.create === 'function') {\n // ParserSuperstructEsque\n return parser.create.bind(parser);\n }\n\n if (typeof parser.assert === 'function') {\n // ParserScaleEsque\n return (value) => {\n parser.assert(value);\n return value as TType;\n };\n }\n\n if (isStandardSchema) {\n // StandardSchemaEsque\n return async (value) => {\n const result = await parser['~standard'].validate(value);\n if (result.issues) {\n throw new StandardSchemaV1Error(result.issues);\n }\n return result.value;\n };\n }\n\n throw new Error('Could not find a validator fn');\n}\n","import type { CombinedDataTransformer } from '../unstable-core-do-not-import';\nimport type { DefaultErrorShape, ErrorFormatter } from './error/formatter';\nimport type { JSONLProducerOptions } from './stream/jsonl';\nimport type { SSEStreamProducerOptions } from './stream/sse';\n\n/**\n * The initial generics that are used in the init function\n * @internal\n */\nexport interface RootTypes {\n ctx: object;\n meta: object;\n errorShape: DefaultErrorShape;\n transformer: boolean;\n}\n\n/**\n * Recommended content types for batch stream responses.\n *\n * `application/json` remains the default for backwards compatibility, while\n * other string values are allowed for tooling or infrastructure compatibility.\n */\nexport type JSONLContentType =\n | 'application/json'\n | 'application/jsonl'\n | 'application/x-ndjson'\n | (string & {});\n\nexport interface JSONLConfig extends Pick<JSONLProducerOptions, 'pingMs'> {\n /**\n * The `content-type` header to use for batch stream responses.\n * Supports any valid content type string.\n * Defaults to `application/json` for backwards compatibility.\n * @default 'application/json'\n */\n contentType?: JSONLContentType;\n}\n\n/**\n * The default check to see if we're in a server\n */\nexport const isServerDefault: boolean =\n typeof window === 'undefined' ||\n 'Deno' in window ||\n // oxlint-disable-next-line typescript/dot-notation\n globalThis.process?.env?.['NODE_ENV'] === 'test' ||\n !!globalThis.process?.env?.['JEST_WORKER_ID'] ||\n !!globalThis.process?.env?.['VITEST_WORKER_ID'];\n\n/**\n * The default check to see if we're in development\n */\nexport function isDevDefault(): boolean {\n // oxlint-disable-next-line typescript/dot-notation\n return globalThis.process?.env['NODE_ENV'] !== 'production';\n}\n\n/**\n * The tRPC root config\n * @internal\n */\nexport interface RootConfig<TTypes extends RootTypes> {\n /**\n * The types that are used in the config\n * @internal\n */\n $types: TTypes;\n /**\n * Use a data transformer\n * @see https://trpc.io/docs/v11/data-transformers\n */\n transformer: CombinedDataTransformer;\n /**\n * Use custom error formatting\n * @see https://trpc.io/docs/v11/error-formatting\n */\n errorFormatter: ErrorFormatter<TTypes['ctx'], TTypes['errorShape']>;\n /**\n * Allow `@trpc/server` to run in non-server environments\n * @warning **Use with caution**, this should likely mainly be used within testing.\n * @default false\n */\n allowOutsideOfServer: boolean;\n /**\n * Is this a server environment?\n * @warning **Use with caution**, this should likely mainly be used within testing.\n * @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test'\n */\n isServer: boolean;\n /**\n * Is this development?\n * Will be used to decide if the API should return stack traces\n * @default process.env.NODE_ENV !== 'production'\n */\n isDev: boolean;\n\n defaultMeta?: TTypes['meta'] extends object ? TTypes['meta'] : never;\n\n /**\n * Options for server-sent events (SSE) subscriptions\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\n sse?: {\n /**\n * Enable server-sent events (SSE) subscriptions\n * @default true\n */\n enabled?: boolean;\n } & Pick<\n SSEStreamProducerOptions,\n 'ping' | 'emitAndEndImmediately' | 'maxDurationMs' | 'client'\n >;\n\n /**\n * Options for batch stream\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\n jsonl?: JSONLConfig;\n experimental?: {};\n}\n\n/**\n * @internal\n */\nexport type CreateRootTypes<TGenerics extends RootTypes> = TGenerics;\n\nexport type AnyRootTypes = CreateRootTypes<{\n ctx: any;\n meta: any;\n errorShape: any;\n transformer: any;\n}>;\n\ntype PartialIf<TCondition extends boolean, TType> = TCondition extends true\n ? Partial<TType>\n : TType;\n\n/**\n * Adds a `createContext` option with a given callback function\n * If context is the default value, then the `createContext` option is optional\n */\nexport type CreateContextCallback<\n TContext,\n TFunction extends (...args: any[]) => any,\n> = PartialIf<\n object extends TContext ? true : false,\n {\n /**\n * @see https://trpc.io/docs/v11/context\n **/\n createContext: TFunction;\n }\n>;\n","import type { inferObservableValue, Observable } from '../observable';\nimport type { ProcedureErrorFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n AnyMiddlewareFunction,\n MiddlewareBuilder,\n MiddlewareFunction,\n MiddlewareResult,\n} from './middleware';\nimport {\n createErrorFormatterMiddleware,\n createInputMiddleware,\n createOutputMiddleware,\n middlewareMarker,\n} from './middleware';\nimport type { inferParser, Parser } from './parser';\nimport { getParseFn } from './parser';\nimport type {\n AnyMutationProcedure,\n AnyProcedure,\n AnyQueryProcedure,\n LegacyObservableSubscriptionProcedure,\n MutationProcedure,\n ProcedureType,\n QueryProcedure,\n SubscriptionProcedure,\n} from './procedure';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { isDevDefault } from './rootConfig';\nimport type { TRPCErrorShape } from './rpc';\nimport type { inferTrackedOutput } from './stream/tracked';\nimport type {\n GetRawInputFn,\n MaybePromise,\n Overwrite,\n Simplify,\n TypeError,\n} from './types';\nimport type { UnsetMarker } from './utils';\nimport { mergeWithoutOverrides } from './utils';\n\ntype IntersectIfDefined<TType, TWith> = TType extends UnsetMarker\n ? TWith\n : TWith extends UnsetMarker\n ? TType\n : Simplify<TType & TWith>;\n\ntype DefaultValue<TValue, TFallback> = TValue extends UnsetMarker\n ? TFallback\n : TValue;\n\ntype FoldErrorShape<TErrorShape, $Shape> =\n | Extract<$Shape, TRPCErrorShape>\n | TErrorShape;\n\ntype inferAsyncIterable<TOutput> =\n TOutput extends AsyncIterable<infer $Yield, infer $Return, infer $Next>\n ? {\n yield: $Yield;\n return: $Return;\n next: $Next;\n }\n : never;\ntype inferSubscriptionOutput<TOutput> =\n TOutput extends AsyncIterable<any>\n ? AsyncIterable<\n inferTrackedOutput<inferAsyncIterable<TOutput>['yield']>,\n inferAsyncIterable<TOutput>['return'],\n inferAsyncIterable<TOutput>['next']\n >\n : TypeError<'Subscription output could not be inferred'>;\n\nexport type CallerOverride<TContext> = (opts: {\n args: unknown[];\n invoke: (opts: ProcedureCallOptions<TContext>) => Promise<unknown>;\n _def: AnyProcedure['_def'];\n}) => Promise<unknown>;\ntype ProcedureBuilderDef<TMeta> = {\n procedure: true;\n inputs: Parser[];\n output?: Parser;\n meta?: TMeta;\n resolver?: ProcedureBuilderResolver;\n middlewares: AnyMiddlewareFunction[];\n /**\n * @deprecated use `type` instead\n */\n mutation?: boolean;\n /**\n * @deprecated use `type` instead\n */\n query?: boolean;\n /**\n * @deprecated use `type` instead\n */\n subscription?: boolean;\n type?: ProcedureType;\n caller?: CallerOverride<unknown>;\n config?: RootConfig<AnyRootTypes>;\n};\n\ntype AnyProcedureBuilderDef = ProcedureBuilderDef<any>;\n\n/**\n * Procedure resolver options (what the `.query()`, `.mutation()`, and `.subscription()` functions receive)\n * @internal\n */\nexport interface ProcedureResolverOptions<\n TContext,\n _TMeta,\n TContextOverridesIn,\n TInputOut,\n> {\n ctx: Simplify<Overwrite<TContext, TContextOverridesIn>>;\n input: TInputOut extends UnsetMarker ? undefined : TInputOut;\n /**\n * The AbortSignal of the request\n */\n signal: AbortSignal | undefined;\n /**\n * The path of the procedure\n */\n path: string;\n /**\n * The index of this call in a batch request.\n * Will be set when the procedure is called as part of a batch.\n */\n batchIndex?: number;\n}\n\n/**\n * A procedure resolver\n */\ntype ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputParserIn,\n $Output,\n> = (\n opts: ProcedureResolverOptions<TContext, TMeta, TContextOverrides, TInputOut>,\n) => MaybePromise<\n // If an output parser is defined, we need to return what the parser expects, otherwise we return the inferred type\n DefaultValue<TOutputParserIn, $Output>\n>;\n\ntype AnyResolver = ProcedureResolver<any, any, any, any, any, any>;\nexport type AnyProcedureBuilder = ProcedureBuilder<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n/**\n * Infer the context type from a procedure builder\n * Useful to create common helper functions for different procedures\n */\nexport type inferProcedureBuilderResolverOptions<\n TProcedureBuilder extends AnyProcedureBuilder,\n> =\n TProcedureBuilder extends ProcedureBuilder<\n infer TContext,\n infer TMeta,\n infer TContextOverrides,\n infer _TInputIn,\n infer TInputOut,\n infer _TOutputIn,\n infer _TOutputOut,\n infer _TCaller,\n infer _TErrorShape\n >\n ? ProcedureResolverOptions<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut extends UnsetMarker\n ? // if input is not set, we don't want to infer it as `undefined` since a procedure further down the chain might have set an input\n unknown\n : TInputOut extends object\n ? Simplify<\n TInputOut & {\n /**\n * Extra input params might have been added by a `.input()` further down the chain\n */\n [keyAddedByInputCallFurtherDown: string]: unknown;\n }\n >\n : TInputOut\n >\n : never;\n\nexport interface ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller extends boolean,\n /**\n * Defaults to `unknown` so that an annotation written without it falls back\n * to the router-wide error shape rather than pinning the procedure to the\n * default one.\n * @see inferProcedureErrorShape\n */\n TErrorShape = unknown,\n> {\n /**\n * Add an input parser to the procedure.\n * @see https://trpc.io/docs/v11/server/validators\n */\n input<$Parser extends Parser>(\n schema: TInputOut extends UnsetMarker\n ? $Parser\n : inferParser<$Parser>['out'] extends Record<string, unknown> | undefined\n ? TInputOut extends Record<string, unknown> | undefined\n ? undefined extends inferParser<$Parser>['out'] // if current is optional the previous must be too\n ? undefined extends TInputOut\n ? $Parser\n : TypeError<'Cannot chain an optional parser to a required parser'>\n : $Parser\n : TypeError<'All input parsers did not resolve to an object'>\n : TypeError<'All input parsers did not resolve to an object'>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n IntersectIfDefined<TInputIn, inferParser<$Parser>['in']>,\n IntersectIfDefined<TInputOut, inferParser<$Parser>['out']>,\n TOutputIn,\n TOutputOut,\n TCaller,\n TErrorShape\n >;\n /**\n * Add an output parser to the procedure.\n * @see https://trpc.io/docs/v11/server/validators\n */\n output<$Parser extends Parser>(\n schema: $Parser,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n IntersectIfDefined<TOutputIn, inferParser<$Parser>['in']>,\n IntersectIfDefined<TOutputOut, inferParser<$Parser>['out']>,\n TCaller,\n TErrorShape\n >;\n /**\n * Add a meta data to the procedure.\n * @see https://trpc.io/docs/v11/server/metadata\n */\n meta(\n meta: TMeta,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller,\n TErrorShape\n >;\n /**\n * Add per procedure error formatters.\n *\n * An error will bubble until a `.errors()` handler returns a shape\n * or it reaches the global errorFormatter\n *\n * @see https://trpc.io/docs/v11/server/error-formatting\n */\n errors<$Shape extends TRPCErrorShape | undefined | void>(\n formatter: ProcedureErrorFormatter<TContext, TContextOverrides, $Shape>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller,\n FoldErrorShape<TErrorShape, $Shape>\n >;\n /**\n * Add a middleware to the procedure.\n * @see https://trpc.io/docs/v11/server/middlewares\n */\n use<$ContextOverridesOut>(\n fn:\n | MiddlewareBuilder<\n Overwrite<TContext, TContextOverrides>,\n TMeta,\n $ContextOverridesOut,\n TInputOut\n >\n | MiddlewareFunction<\n TContext,\n TMeta,\n TContextOverrides,\n $ContextOverridesOut,\n TInputOut\n >,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverridesOut>,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n TCaller,\n TErrorShape\n >;\n\n /**\n * @deprecated use {@link concat} instead\n */\n unstable_concat<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n $ErrorShape,\n >(\n builder: Overwrite<TContext, TContextOverrides> extends $Context\n ? TMeta extends $Meta\n ? ProcedureBuilder<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n TCaller,\n $ErrorShape\n >\n : TypeError<'Meta mismatch'>\n : TypeError<'Context mismatch'>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverrides>,\n IntersectIfDefined<TInputIn, $InputIn>,\n IntersectIfDefined<TInputOut, $InputOut>,\n IntersectIfDefined<TOutputIn, $OutputIn>,\n IntersectIfDefined<TOutputOut, $OutputOut>,\n TCaller,\n FoldErrorShape<TErrorShape, $ErrorShape>\n >;\n\n /**\n * Combine two procedure builders\n */\n concat<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n $ErrorShape,\n >(\n builder: Overwrite<TContext, TContextOverrides> extends $Context\n ? TMeta extends $Meta\n ? ProcedureBuilder<\n $Context,\n $Meta,\n $ContextOverrides,\n $InputIn,\n $InputOut,\n $OutputIn,\n $OutputOut,\n TCaller,\n $ErrorShape\n >\n : TypeError<'Meta mismatch'>\n : TypeError<'Context mismatch'>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n Overwrite<TContextOverrides, $ContextOverrides>,\n IntersectIfDefined<TInputIn, $InputIn>,\n IntersectIfDefined<TInputOut, $InputOut>,\n IntersectIfDefined<TOutputIn, $OutputIn>,\n IntersectIfDefined<TOutputOut, $OutputOut>,\n TCaller,\n FoldErrorShape<TErrorShape, $ErrorShape>\n >;\n /**\n * Query procedure\n * @see https://trpc.io/docs/v11/concepts#vocabulary\n */\n query<$Output>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? (\n input: DefaultValue<TInputIn, void>,\n ) => Promise<DefaultValue<TOutputOut, $Output>>\n : QueryProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: DefaultValue<TOutputOut, $Output>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n\n /**\n * Mutation procedure\n * @see https://trpc.io/docs/v11/concepts#vocabulary\n */\n mutation<$Output>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? (\n input: DefaultValue<TInputIn, void>,\n ) => Promise<DefaultValue<TOutputOut, $Output>>\n : MutationProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: DefaultValue<TOutputOut, $Output>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n\n /**\n * Subscription procedure\n * @see https://trpc.io/docs/v11/server/subscriptions\n */\n subscription<$Output extends AsyncIterable<any, void, any>>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? TypeError<'Not implemented'>\n : SubscriptionProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: inferSubscriptionOutput<DefaultValue<TOutputOut, $Output>>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n /**\n * @deprecated Using subscriptions with an observable is deprecated. Use an async generator instead.\n * This feature will be removed in v12 of tRPC.\n * @see https://trpc.io/docs/v11/server/subscriptions\n */\n subscription<$Output extends Observable<any, any>>(\n resolver: ProcedureResolver<\n TContext,\n TMeta,\n TContextOverrides,\n TInputOut,\n TOutputIn,\n $Output\n >,\n ): TCaller extends true\n ? TypeError<'Not implemented'>\n : LegacyObservableSubscriptionProcedure<{\n input: DefaultValue<TInputIn, void>;\n output: inferObservableValue<DefaultValue<TOutputOut, $Output>>;\n meta: TMeta;\n errorShape: TErrorShape;\n }>;\n /**\n * Overrides the way a procedure is invoked\n * Do not use this unless you know what you're doing - this is an experimental API\n */\n experimental_caller(\n caller: CallerOverride<TContext>,\n ): ProcedureBuilder<\n TContext,\n TMeta,\n TContextOverrides,\n TInputIn,\n TInputOut,\n TOutputIn,\n TOutputOut,\n true,\n TErrorShape\n >;\n /**\n * @internal\n */\n _def: ProcedureBuilderDef<TMeta>;\n}\n\ntype ProcedureBuilderResolver = (\n opts: ProcedureResolverOptions<any, any, any, any>,\n) => Promise<unknown>;\n\nfunction createNewBuilder(\n def1: AnyProcedureBuilderDef,\n def2: Partial<AnyProcedureBuilderDef>,\n): AnyProcedureBuilder {\n const { middlewares = [], inputs, meta, config, ...rest } = def2;\n\n // TODO: maybe have a fn here to warn about calls\n return createBuilder({\n ...mergeWithoutOverrides(def1, rest),\n config: def1.config ?? config,\n inputs: [...def1.inputs, ...(inputs ?? [])],\n middlewares: [...def1.middlewares, ...middlewares],\n meta: def1.meta && meta ? { ...def1.meta, ...meta } : (meta ?? def1.meta),\n });\n}\n\nexport function createBuilder<TContext, TMeta, TErrorShape = unknown>(\n initDef: Partial<AnyProcedureBuilderDef> = {},\n): ProcedureBuilder<\n TContext,\n TMeta,\n object,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n false,\n TErrorShape\n> {\n const _def: AnyProcedureBuilderDef = {\n procedure: true,\n inputs: [],\n middlewares: [],\n ...initDef,\n };\n\n const builder: AnyProcedureBuilder = {\n _def,\n input(input) {\n const parser = getParseFn(input as Parser);\n return createNewBuilder(_def, {\n inputs: [input as Parser],\n middlewares: [createInputMiddleware(parser)],\n });\n },\n output(output: Parser) {\n const parser = getParseFn(output);\n return createNewBuilder(_def, {\n output,\n middlewares: [createOutputMiddleware(parser)],\n });\n },\n meta(meta) {\n return createNewBuilder(_def, {\n meta,\n });\n },\n errors(formatter) {\n return createNewBuilder(_def, {\n middlewares: [\n createErrorFormatterMiddleware(\n formatter,\n _def.config?.isDev ?? isDevDefault(),\n ),\n ],\n });\n },\n use(middlewareBuilderOrFn) {\n // Distinguish between a middleware builder and a middleware function\n const middlewares =\n '_middlewares' in middlewareBuilderOrFn\n ? middlewareBuilderOrFn._middlewares\n : [middlewareBuilderOrFn];\n\n return createNewBuilder(_def, {\n middlewares: middlewares,\n });\n },\n unstable_concat(builder) {\n return createNewBuilder(_def, (builder as AnyProcedureBuilder)._def);\n },\n concat(builder) {\n return createNewBuilder(_def, (builder as AnyProcedureBuilder)._def);\n },\n query(resolver) {\n return createResolver(\n { ..._def, type: 'query' },\n resolver,\n ) as AnyQueryProcedure;\n },\n mutation(resolver) {\n return createResolver(\n { ..._def, type: 'mutation' },\n resolver,\n ) as AnyMutationProcedure;\n },\n subscription(resolver: ProcedureResolver<any, any, any, any, any, any>) {\n return createResolver({ ..._def, type: 'subscription' }, resolver) as any;\n },\n experimental_caller(caller) {\n return createNewBuilder(_def, {\n caller,\n }) as any;\n },\n };\n\n return builder;\n}\n\nfunction createResolver(\n _defIn: AnyProcedureBuilderDef & { type: ProcedureType },\n resolver: AnyResolver,\n) {\n const finalBuilder = createNewBuilder(_defIn, {\n resolver,\n middlewares: [\n async function resolveMiddleware(opts) {\n const data = await resolver(opts);\n return {\n marker: middlewareMarker,\n ok: true,\n data,\n ctx: opts.ctx,\n } as const;\n },\n ],\n });\n const _def: AnyProcedure['_def'] = {\n ...finalBuilder._def,\n type: _defIn.type,\n experimental_caller: Boolean(finalBuilder._def.caller),\n meta: finalBuilder._def.meta,\n $types: null as any,\n };\n\n const invoke = createProcedureCaller(finalBuilder._def);\n const callerOverride = finalBuilder._def.caller;\n if (!callerOverride) {\n return invoke;\n }\n const callerWrapper = async (...args: unknown[]) => {\n return await callerOverride({\n args,\n invoke,\n _def: _def,\n });\n };\n\n callerWrapper._def = _def;\n\n return callerWrapper;\n}\n\n/**\n * @internal\n */\nexport interface ProcedureCallOptions<TContext> {\n ctx: TContext;\n getRawInput: GetRawInputFn;\n input?: unknown;\n path: string;\n type: ProcedureType;\n signal: AbortSignal | undefined;\n /**\n * The index of this call in a batch request.\n */\n batchIndex: number;\n}\n\nconst codeblock = `\nThis is a client-only function.\nIf you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls\n`.trim();\n\n// run the middlewares recursively with the resolver as the last one\nasync function callRecursive(\n index: number,\n _def: AnyProcedureBuilderDef,\n opts: ProcedureCallOptions<any>,\n): Promise<MiddlewareResult<any>> {\n try {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n const middleware = _def.middlewares[index]!;\n const result = await middleware({\n ...opts,\n meta: _def.meta,\n input: opts.input,\n next(_nextOpts?: any) {\n const nextOpts = _nextOpts as\n | {\n ctx?: Record<string, unknown>;\n input?: unknown;\n getRawInput?: GetRawInputFn;\n }\n | undefined;\n\n return callRecursive(index + 1, _def, {\n ...opts,\n ctx: nextOpts?.ctx ? { ...opts.ctx, ...nextOpts.ctx } : opts.ctx,\n input: nextOpts && 'input' in nextOpts ? nextOpts.input : opts.input,\n getRawInput: nextOpts?.getRawInput ?? opts.getRawInput,\n });\n },\n });\n\n return result;\n } catch (cause) {\n return {\n ok: false,\n error: getTRPCErrorFromUnknown(cause),\n marker: middlewareMarker,\n };\n }\n}\n\nfunction createProcedureCaller(_def: AnyProcedureBuilderDef): AnyProcedure {\n async function procedure(opts: ProcedureCallOptions<unknown>) {\n // is direct server-side call\n if (!opts || !('getRawInput' in opts)) {\n throw new Error(codeblock);\n }\n\n // there's always at least one \"next\" since we wrap this.resolver in a middleware\n const result = await callRecursive(0, _def, opts);\n\n if (!result) {\n throw new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n message:\n 'No result from middlewares - did you forget to `return next()`?',\n });\n }\n if (!result.ok) {\n // re-throw original error\n throw result.error;\n }\n return result.data;\n }\n\n procedure._def = _def;\n procedure.procedure = true;\n procedure.meta = _def.meta;\n\n // FIXME typecast shouldn't be needed - fixittt\n return procedure as unknown as AnyProcedure;\n}\n","import {\n defaultFormatter,\n type DefaultErrorShape,\n type ErrorFormatter,\n} from './error/formatter';\nimport type { MiddlewareBuilder, MiddlewareFunction } from './middleware';\nimport { createMiddlewareFactory } from './middleware';\nimport type { ProcedureBuilder } from './procedureBuilder';\nimport { createBuilder } from './procedureBuilder';\nimport type { AnyRootTypes, CreateRootTypes } from './rootConfig';\nimport { isDevDefault, isServerDefault, type RootConfig } from './rootConfig';\nimport type {\n AnyRouter,\n MergeRouters,\n RouterBuilder,\n RouterCallerFactory,\n} from './router';\nimport {\n createCallerFactory,\n createRouterFactory,\n mergeRouters,\n} from './router';\nimport type { DataTransformerOptions } from './transformer';\nimport { defaultTransformer, getDataTransformer } from './transformer';\nimport type { Unwrap, ValidateShape } from './types';\nimport type { UnsetMarker } from './utils';\n\ntype inferErrorFormatterShape<TType> =\n TType extends ErrorFormatter<any, infer TShape> ? TShape : DefaultErrorShape;\n/** @internal */\nexport interface RuntimeConfigOptions<\n TContext extends object,\n TMeta extends object,\n> extends Partial<\n Omit<\n RootConfig<{\n ctx: TContext;\n meta: TMeta;\n errorShape: any;\n transformer: any;\n }>,\n '$types' | 'transformer'\n >\n> {\n /**\n * Use a data transformer\n * @see https://trpc.io/docs/v11/data-transformers\n */\n transformer?: DataTransformerOptions;\n}\n\ntype ContextCallback = (...args: any[]) => object | Promise<object>;\n\nexport interface TRPCRootObject<\n TContext extends object,\n TMeta extends object,\n TOptions extends RuntimeConfigOptions<TContext, TMeta>,\n $Root extends AnyRootTypes = {\n ctx: TContext;\n meta: TMeta;\n errorShape: undefined extends TOptions['errorFormatter']\n ? DefaultErrorShape\n : inferErrorFormatterShape<TOptions['errorFormatter']>;\n transformer: undefined extends TOptions['transformer'] ? false : true;\n },\n> {\n /**\n * Your router config\n * @internal\n */\n _config: RootConfig<$Root>;\n\n /**\n * Builder object for creating procedures\n * @see https://trpc.io/docs/v11/server/procedures\n */\n procedure: ProcedureBuilder<\n TContext,\n TMeta,\n object,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n UnsetMarker,\n false,\n $Root['errorShape']\n >;\n\n /**\n * Create reusable middlewares\n * @see https://trpc.io/docs/v11/server/middlewares\n */\n middleware: <$ContextOverrides>(\n fn: MiddlewareFunction<TContext, TMeta, object, $ContextOverrides, unknown>,\n ) => MiddlewareBuilder<TContext, TMeta, $ContextOverrides, unknown>;\n\n /**\n * Create a router\n * @see https://trpc.io/docs/v11/server/routers\n */\n router: RouterBuilder<$Root>;\n\n /**\n * Merge Routers\n * @see https://trpc.io/docs/v11/server/merging-routers\n */\n mergeRouters: <TRouters extends AnyRouter[]>(\n ...routerList: [...TRouters]\n ) => MergeRouters<TRouters>;\n\n /**\n * Create a server-side caller for a router\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCallerFactory: RouterCallerFactory<$Root>;\n}\n\nclass TRPCBuilder<TContext extends object, TMeta extends object> {\n /**\n * Add a context shape as a generic to the root object\n * @see https://trpc.io/docs/v11/server/context\n */\n context<TNewContext extends object | ContextCallback>() {\n return new TRPCBuilder<\n TNewContext extends ContextCallback ? Unwrap<TNewContext> : TNewContext,\n TMeta\n >();\n }\n\n /**\n * Add a meta shape as a generic to the root object\n * @see https://trpc.io/docs/v11/quickstart\n */\n meta<TNewMeta extends object>() {\n return new TRPCBuilder<TContext, TNewMeta>();\n }\n\n /**\n * Create the root object\n * @see https://trpc.io/docs/v11/server/routers#initialize-trpc\n */\n create<TOptions extends RuntimeConfigOptions<TContext, TMeta>>(\n opts?: ValidateShape<TOptions, RuntimeConfigOptions<TContext, TMeta>>,\n ): TRPCRootObject<TContext, TMeta, TOptions> {\n type $Root = CreateRootTypes<{\n ctx: TContext;\n meta: TMeta;\n errorShape: undefined extends TOptions['errorFormatter']\n ? DefaultErrorShape\n : inferErrorFormatterShape<TOptions['errorFormatter']>;\n transformer: undefined extends TOptions['transformer'] ? false : true;\n }>;\n\n const config: RootConfig<$Root> = {\n ...opts,\n transformer: getDataTransformer(opts?.transformer ?? defaultTransformer),\n isDev: opts?.isDev ?? isDevDefault(),\n allowOutsideOfServer: opts?.allowOutsideOfServer ?? false,\n errorFormatter: opts?.errorFormatter ?? defaultFormatter,\n isServer: opts?.isServer ?? isServerDefault,\n /**\n * These are just types, they can't be used at runtime\n * @internal\n */\n $types: null as any,\n };\n\n {\n // Server check\n const isServer: boolean = opts?.isServer ?? isServerDefault;\n\n if (!isServer && opts?.allowOutsideOfServer !== true) {\n throw new Error(\n `You're trying to use @trpc/server in a non-server environment. This is not supported by default.`,\n );\n }\n }\n return {\n /**\n * Your router config\n * @internal\n */\n _config: config,\n /**\n * Builder object for creating procedures\n * @see https://trpc.io/docs/v11/server/procedures\n */\n procedure: createBuilder<\n $Root['ctx'],\n $Root['meta'],\n $Root['errorShape']\n >({\n meta: opts?.defaultMeta,\n config,\n }),\n /**\n * Create reusable middlewares\n * @see https://trpc.io/docs/v11/server/middlewares\n */\n middleware: createMiddlewareFactory<$Root['ctx'], $Root['meta']>(),\n /**\n * Create a router\n * @see https://trpc.io/docs/v11/server/routers\n */\n router: createRouterFactory<$Root>(config),\n /**\n * Merge Routers\n * @see https://trpc.io/docs/v11/server/merging-routers\n */\n mergeRouters,\n /**\n * Create a server-side caller for a router\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCallerFactory: createCallerFactory<$Root>(),\n };\n }\n}\n\n/**\n * Builder to initialize the tRPC root object - use this exactly once per backend\n * @see https://trpc.io/docs/v11/quickstart\n */\nexport const initTRPC = new TRPCBuilder();\nexport type { TRPCBuilder };\n"],"mappings":";;;;;;AAeA,MAAa,mBAAmB;;;;AAwHhC,SAAgB,0BAIZ;CACF,SAAS,sBACP,aACsB;EACtB,OAAO;GACL,cAAc;GACd,cAAc,uBAAuB;IACnC,MAAM,kBACJ,kBAAkB,wBACd,sBAAsB,eACtB,CAAC,qBAAqB;IAE5B,OAAO,sBAAsB,CAAC,GAAG,aAAa,GAAG,eAAe,CAAC;GACnE;EACF;CACF;CAEA,SAAS,iBACP,IAOkE;EAClE,OAAO,sBAAsB,CAAC,EAAE,CAAC;CACnC;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,2CAML,EACN,QAAQ,wBAIN,EACJ;;;;;AAMA,SAAgB,sBAA8B,OAAwB;CACpE,MAAM,kBACJ,eAAe,yBAAyB,MAAM;EAC5C,IAAI;EAEJ,MAAM,WAAW,MAAM,KAAK,YAAY;EACxC,IAAI;GACF,cAAc,MAAM,MAAM,QAAQ;EACpC,SAAS,OAAO;GACd,MAAM,IAAI,UAAU;IAClB,MAAM;IACN;GACF,CAAC;EACH;EAGA,MAAM,gBACJ,SAAS,KAAK,KAAK,KAAK,SAAS,WAAW,IAAA,eAAA,eAAA,CAAA,GAEnC,KAAK,KAAA,GACL,WACL,IACA;EAEN,OAAO,KAAK,KAAK,EAAE,OAAO,cAAc,CAAC;CAC3C;CACF,gBAAgB,QAAQ;CACxB,OAAO;AACT;;;;AAKA,SAAgB,+BACd,WACA,OACA;CACA,MAAM,kBACJ,eAAe,yBAAyB,MAAM;EAC5C,MAAM,aAAa,UAAgC;GAEjD,IAAI,sBAAsB,KAAK,GAC7B,OAAO;GAGT,MAAM,QAAQ,UAAU;IACtB;IACA,MAAM,KAAK;IACX,MAAM,KAAK;IACX,OAAO,KAAK;IACZ,KAAK,KAAK;IACV,OAAO,qBAAqB;KAC1B;KACA,MAAM,KAAK;KACX;IACF,CAAC;GACH,CAAC;GAED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AAA,KAAA,IAAA,wBAAwB;GACpD,iBAAA,uBAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAgB,KAAM,oBAAA,QAAA,yBAAA,KAAA,IAAA,uBAAkB;GACxC,WAAA,iBAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAU,KAAM,cAAA,QAAA,mBAAA,KAAA,IAAA,iBAAY;;;;;GAK5B,QAAQ;EACV,CAAA;;EAME,IAAI,GAAA,kBAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAFsB,KAAM,cAAA,QAAA,oBAAA,KAAA,IAAA,kBAAY,qBAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAE3B,KAAM,0BAAyB,MAC9C,MAAM,IAAI,MACR,kGACF;EAGJ,OAAO;;;;;GAKL,SAAS;;;;;GAKT,WAAW,cAIT;IACA,MAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAM,KAAM;IACZ;GACF,CAAC;;;;;GAKD,YAAY,wBAAqD;;;;;GAKjE,QAAQ,oBAA2B,MAAM;;;;;GAKzC;;;;;GAKA,qBAAqB,oBAA2B;EAClD;CACF;AACF,EAMwC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { m as run } from "./codes-C9N0z0an.mjs";
|
|
2
2
|
import { n as _objectSpread2, t as getErrorShape } from "./getErrorShape-zlj81BiC.mjs";
|
|
3
3
|
import { _ as transformTRPCResponse, b as getTRPCErrorFromUnknown, v as TRPCError } from "./asyncGeneratorDelegate-FcEJT04i.mjs";
|
|
4
|
-
import { h as isAbortError, t as resolveResponse } from "./resolveResponse-
|
|
4
|
+
import { h as isAbortError, t as resolveResponse } from "./resolveResponse-DksrxZ2k.mjs";
|
|
5
5
|
import { IncomingMessage } from "node:http";
|
|
6
6
|
//#region src/adapters/node-http/incomingMessageToRequest.ts
|
|
7
7
|
function createBody(req, opts) {
|
|
@@ -246,4 +246,4 @@ async function nodeHTTPRequestHandler(opts) {
|
|
|
246
246
|
export { incomingMessageToRequest as i, nodeHTTPRequestHandler as n, createURL as r, internal_exceptionHandler as t };
|
|
247
247
|
|
|
248
248
|
|
|
249
|
-
//# sourceMappingURL=node-http-
|
|
249
|
+
//# sourceMappingURL=node-http-ChhZEv1k.mjs.map
|