@orpc/contract 2.0.0-beta.48 → 2.0.0-beta.49

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.
Files changed (81) hide show
  1. package/README.md +4 -4
  2. package/dist/builder-variants.d.ts +103 -0
  3. package/dist/builder.d.ts +78 -0
  4. package/dist/builder.js +112 -0
  5. package/dist/client-factory.d.ts +24 -0
  6. package/dist/client-factory.js +38 -0
  7. package/dist/error-factory.d.ts +80 -0
  8. package/dist/error-factory.js +121 -0
  9. package/dist/error-utils.d.ts +5 -0
  10. package/dist/error-utils.js +40 -0
  11. package/dist/error.d.ts +45 -0
  12. package/dist/error.js +20 -0
  13. package/dist/index.d.ts +62 -0
  14. package/dist/index.js +31 -0
  15. package/dist/meta-built-in.d.ts +30 -0
  16. package/dist/meta-built-in.js +54 -0
  17. package/dist/meta-utils.d.ts +58 -0
  18. package/dist/meta-utils.js +76 -0
  19. package/dist/meta.d.ts +53 -0
  20. package/dist/meta.js +13 -0
  21. package/dist/plugins/index.d.ts +12 -0
  22. package/dist/plugins/index.js +12 -0
  23. package/dist/plugins/request-validation.d.ts +28 -0
  24. package/dist/plugins/request-validation.js +55 -0
  25. package/dist/plugins/response-validation.d.ts +15 -0
  26. package/dist/plugins/response-validation.js +72 -0
  27. package/dist/procedure-client.d.ts +5 -0
  28. package/dist/procedure.d.ts +28 -0
  29. package/dist/procedure.js +28 -0
  30. package/dist/router-client.d.ts +13 -0
  31. package/dist/router-utils.d.ts +30 -0
  32. package/dist/router-utils.js +79 -0
  33. package/dist/router.d.ts +52 -0
  34. package/dist/schema-built-in.d.ts +23 -0
  35. package/dist/schema-built-in.js +76 -0
  36. package/dist/schema-utils.d.ts +20 -0
  37. package/dist/schema-utils.js +44 -0
  38. package/dist/schema.d.ts +25 -0
  39. package/package.json +28 -30
  40. package/dist/builder-variants.d.mts +0 -113
  41. package/dist/builder.d.mts +0 -78
  42. package/dist/builder.mjs +0 -71
  43. package/dist/client-factory.d.mts +0 -24
  44. package/dist/client-factory.mjs +0 -34
  45. package/dist/error-factory.d.mts +0 -87
  46. package/dist/error-factory.mjs +0 -75
  47. package/dist/error-utils.d.mts +0 -11
  48. package/dist/error-utils.mjs +0 -43
  49. package/dist/error.d.mts +0 -41
  50. package/dist/error.mjs +0 -12
  51. package/dist/index.d.mts +0 -62
  52. package/dist/index.mjs +0 -25
  53. package/dist/meta-built-in.d.mts +0 -38
  54. package/dist/meta-built-in.mjs +0 -40
  55. package/dist/meta-utils.d.mts +0 -62
  56. package/dist/meta-utils.mjs +0 -33
  57. package/dist/meta.d.mts +0 -61
  58. package/dist/meta.mjs +0 -11
  59. package/dist/plugins/index.d.mts +0 -12
  60. package/dist/plugins/index.mjs +0 -8
  61. package/dist/plugins/request-validation.d.mts +0 -28
  62. package/dist/plugins/request-validation.mjs +0 -46
  63. package/dist/plugins/response-validation.d.mts +0 -15
  64. package/dist/plugins/response-validation.mjs +0 -53
  65. package/dist/procedure-client.d.mts +0 -10
  66. package/dist/procedure.d.mts +0 -36
  67. package/dist/procedure.mjs +0 -19
  68. package/dist/router-client.d.mts +0 -14
  69. package/dist/router-utils.d.mts +0 -34
  70. package/dist/router-utils.mjs +0 -67
  71. package/dist/router.d.mts +0 -42
  72. package/dist/schema-built-in.d.mts +0 -28
  73. package/dist/schema-built-in.mjs +0 -73
  74. package/dist/schema-utils.d.mts +0 -26
  75. package/dist/schema-utils.mjs +0 -29
  76. package/dist/schema.d.mts +0 -31
  77. /package/dist/{builder-variants.mjs → builder-variants.js} +0 -0
  78. /package/dist/{procedure-client.mjs → procedure-client.js} +0 -0
  79. /package/dist/{router-client.mjs → router-client.js} +0 -0
  80. /package/dist/{router.mjs → router.js} +0 -0
  81. /package/dist/{schema.mjs → schema.js} +0 -0
@@ -0,0 +1,45 @@
1
+ import type { ORPCError, ORPCErrorCode } from '@orpc/client';
2
+ import type { AnySchema, InferSchemaOutput, SchemaIssue } from './schema.ts';
3
+ export interface ErrorMapItem {
4
+ /**
5
+ * Default message, can be overridden when constructing an error.
6
+ */
7
+ message?: string | undefined;
8
+ /**
9
+ * Schema used to type and validate the error data.
10
+ */
11
+ data?: AnySchema | undefined;
12
+ }
13
+ /**
14
+ * Map of error codes to their definitions, as passed to `.errors(...)`.
15
+ * Errors defined here remain properly typed on the client.
16
+ *
17
+ * @see {@link https://orpc.dev/docs/metadata | Metadata}
18
+ */
19
+ export type ErrorMap = {
20
+ [key in ORPCErrorCode]?: ErrorMapItem;
21
+ };
22
+ export type ORPCErrorFromErrorMap<TErrorMap extends ErrorMap> = {
23
+ [K in keyof TErrorMap]: TErrorMap[K] extends ErrorMapItem ? ORPCError<K & ORPCErrorCode, TErrorMap[K]['data'] extends AnySchema ? InferSchemaOutput<TErrorMap[K]['data']> : unknown> : never;
24
+ }[keyof TErrorMap];
25
+ export interface ValidationErrorOptions extends ErrorOptions {
26
+ message: string;
27
+ issues: readonly SchemaIssue[];
28
+ invalidData: unknown;
29
+ }
30
+ /**
31
+ * Error thrown when input, output, or error data fails schema validation,
32
+ * carrying the standard-schema `issues` and the invalid data.
33
+ * Usually found as the `cause` of an `ORPCError`.
34
+ *
35
+ * @see {@link https://orpc.dev/docs/recipes/validation-customization | Validation Customization}
36
+ */
37
+ export declare class ValidationError extends Error {
38
+ name: string;
39
+ /**
40
+ * This array is readonly because the upstream Standard Schema returns readonly issues.
41
+ */
42
+ issues: readonly SchemaIssue[];
43
+ invalidData: unknown;
44
+ constructor(options: ValidationErrorOptions);
45
+ }
package/dist/error.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Error thrown when input, output, or error data fails schema validation,
3
+ * carrying the standard-schema `issues` and the invalid data.
4
+ * Usually found as the `cause` of an `ORPCError`.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/recipes/validation-customization | Validation Customization}
7
+ */
8
+ export class ValidationError extends Error {
9
+ name = 'ValidationError';
10
+ /**
11
+ * This array is readonly because the upstream Standard Schema returns readonly issues.
12
+ */
13
+ issues;
14
+ invalidData;
15
+ constructor(options) {
16
+ super(options.message, options);
17
+ this.issues = options.issues;
18
+ this.invalidData = options.invalidData;
19
+ }
20
+ }
@@ -0,0 +1,62 @@
1
+ export * from './builder.ts';
2
+ export * from './builder-variants.ts';
3
+ export * from './client-factory.ts';
4
+ export * from './error.ts';
5
+ export * from './error-factory.ts';
6
+ export * from './error-utils.ts';
7
+ export * from './meta.ts';
8
+ export * from './meta-built-in.ts';
9
+ export * from './meta-utils.ts';
10
+ export * from './procedure.ts';
11
+ export type {
12
+ /**
13
+ * @deprecated Use `AnyProcedureContract` instead.
14
+ */
15
+ AnyProcedureContract as AnyContractProcedure, } from './procedure.ts';
16
+ export * from './procedure-client.ts';
17
+ export * from './router.ts';
18
+ export type {
19
+ /**
20
+ * @deprecated Use `RouterContract` instead.
21
+ */
22
+ RouterContract as AnyContractRouter,
23
+ /**
24
+ * @deprecated Use `InferRouterContractErrorMap` instead.
25
+ */
26
+ InferRouterContractErrorMap as InferContractRouterErrorMap,
27
+ /**
28
+ * @deprecated Use `InferRouterContractInputs` instead.
29
+ */
30
+ InferRouterContractInputs as InferContractRouterInputs,
31
+ /**
32
+ * @deprecated Use `InferRouterContractOutputs` instead.
33
+ */
34
+ InferRouterContractOutputs as InferContractRouterOutputs, } from './router.ts';
35
+ export * from './router-client.ts';
36
+ export type {
37
+ /**
38
+ * @deprecated Use `RouterContractClient` instead.
39
+ */
40
+ RouterContractClient as ContractRouterClient, } from './router-client.ts';
41
+ export { getProcedureContractOrThrow, getRouterContract, minifyRouterContract, } from './router-utils.ts';
42
+ export type { AugmentContractRouterOptions, AugmentedContractRouter } from './router-utils.ts';
43
+ export {
44
+ /**
45
+ * @deprecated Use `getRouterContract` instead.
46
+ */
47
+ getRouterContract as getContractRouter,
48
+ /**
49
+ * @deprecated Use `minifyRouterContract` instead.
50
+ */
51
+ minifyRouterContract as minifyContractRouter, } from './router-utils.ts';
52
+ export * from './schema.ts';
53
+ export { asyncIteratorObject, getAsyncIteratorObjectSchemasDetails } from './schema-built-in.ts';
54
+ export type { AsyncIteratorObjectSchemasDetails } from './schema-built-in.ts';
55
+ export {
56
+ /**
57
+ * @deprecated Use `asyncIteratorObject` instead.
58
+ */
59
+ asyncIteratorObject as eventIterator, } from './schema-built-in.ts';
60
+ export * from './schema-utils.ts';
61
+ export type { Client, ClientContext, ClientOptions, ClientRest, FriendlyClientOptions, } from '@orpc/client';
62
+ export type { AsyncIteratorClass, PromiseWithError, Registry, ThrowableError } from '@orpc/shared';
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ export * from './builder.js';
2
+ export * from './builder-variants.js';
3
+ export * from './client-factory.js';
4
+ export * from './error.js';
5
+ export * from './error-factory.js';
6
+ export * from './error-utils.js';
7
+ export * from './meta.js';
8
+ export * from './meta-built-in.js';
9
+ export * from './meta-utils.js';
10
+ export * from './procedure.js';
11
+ export * from './procedure-client.js';
12
+ export * from './router.js';
13
+ export * from './router-client.js';
14
+ export { getProcedureContractOrThrow, getRouterContract, minifyRouterContract, } from './router-utils.js';
15
+ export {
16
+ /**
17
+ * @deprecated Use `getRouterContract` instead.
18
+ */
19
+ getRouterContract as getContractRouter,
20
+ /**
21
+ * @deprecated Use `minifyRouterContract` instead.
22
+ */
23
+ minifyRouterContract as minifyContractRouter, } from './router-utils.js';
24
+ export * from './schema.js';
25
+ export { asyncIteratorObject, getAsyncIteratorObjectSchemasDetails } from './schema-built-in.js';
26
+ export {
27
+ /**
28
+ * @deprecated Use `asyncIteratorObject` instead.
29
+ */
30
+ asyncIteratorObject as eventIterator, } from './schema-built-in.js';
31
+ export * from './schema-utils.js';
@@ -0,0 +1,30 @@
1
+ import type { ErrorMap } from './error.ts';
2
+ import type { Meta, MetaPlugin } from './meta.ts';
3
+ import type { RouterContract } from './router.ts';
4
+ import type { AnySchema } from './schema.ts';
5
+ export interface PathMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
6
+ name: '~path';
7
+ }
8
+ /**
9
+ * Built-in metadata plugins.
10
+ * `meta.path` records a procedure contract's path inside the root contract,
11
+ * which is required for the contract client factory pattern.
12
+ *
13
+ * @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
14
+ */
15
+ export declare const meta: {
16
+ path<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(path: string[]): PathMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
17
+ };
18
+ export declare function getPathMeta(procedureOrLazy: {
19
+ '~orpc': {
20
+ meta: Meta;
21
+ };
22
+ }): string[] | undefined;
23
+ /**
24
+ * Resolve the base path of a contract from the first procedure-contract
25
+ * that defines `meta.path`: its `meta.path` minus its path inside the given contract.
26
+ * For a procedure-contract, this is its `meta.path` itself.
27
+ *
28
+ * Returns `undefined` when no procedure-contract defines `meta.path`.
29
+ */
30
+ export declare function resolveBasePathMeta(contract: RouterContract, currentPath?: string[]): string[] | undefined;
@@ -0,0 +1,54 @@
1
+ import { isNonPrimitive } from '@orpc/shared';
2
+ import { ProcedureContract } from './procedure.js';
3
+ /**
4
+ * Built-in metadata plugins.
5
+ * `meta.path` records a procedure contract's path inside the root contract,
6
+ * which is required for the contract client factory pattern.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
9
+ */
10
+ export const meta = {
11
+ path(path) {
12
+ return {
13
+ name: '~path',
14
+ init(meta) {
15
+ return {
16
+ ...meta,
17
+ '~path': path,
18
+ };
19
+ },
20
+ };
21
+ },
22
+ };
23
+ export function getPathMeta(procedureOrLazy) {
24
+ return procedureOrLazy['~orpc'].meta['~path'];
25
+ }
26
+ /**
27
+ * Resolve the base path of a contract from the first procedure-contract
28
+ * that defines `meta.path`: its `meta.path` minus its path inside the given contract.
29
+ * For a procedure-contract, this is its `meta.path` itself.
30
+ *
31
+ * Returns `undefined` when no procedure-contract defines `meta.path`.
32
+ */
33
+ export function resolveBasePathMeta(contract, currentPath = []) {
34
+ if (contract instanceof ProcedureContract) {
35
+ const path = getPathMeta(contract);
36
+ if (!path) {
37
+ return undefined;
38
+ }
39
+ const base = path.slice(0, Math.max(0, path.length - currentPath.length));
40
+ if (currentPath.some((key, i) => path[base.length + i] !== key)) {
41
+ throw new TypeError(`Procedure contract at "${currentPath.join('.')}" defines meta.path "${path.join('.')}" that does not match its path inside the given router contract.`);
42
+ }
43
+ return base;
44
+ }
45
+ if (isNonPrimitive(contract)) {
46
+ for (const [key, child] of Object.entries(contract)) {
47
+ const base = resolveBasePathMeta(child, [...currentPath, key]);
48
+ if (base !== undefined) {
49
+ return base;
50
+ }
51
+ }
52
+ }
53
+ return undefined;
54
+ }
@@ -0,0 +1,58 @@
1
+ import type { ErrorMap } from './error.ts';
2
+ import type { AnyMetaPlugin, Meta, MetaPlugin } from './meta.ts';
3
+ import type { AnySchema } from './schema.ts';
4
+ export declare function resolveMetaPlugins<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(baseMeta: Meta, existingPlugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[] | undefined, incomingPlugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[] | undefined): [meta: Meta, plugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[]];
5
+ /**
6
+ * Quickly defines a meta plugin factory and reader.
7
+ *
8
+ * @example Mark a procedure as requiring authentication and read it in middleware.
9
+ * ```ts
10
+ * interface AuthMeta {
11
+ * required?: boolean
12
+ * scope?: 'user' | 'admin'
13
+ * }
14
+ *
15
+ * const [authMeta, getAuthMeta] = defineMeta(
16
+ * 'auth',
17
+ * (incoming: AuthMeta, current) => ({ ...current, ...incoming }),
18
+ * )
19
+ *
20
+ * const deletePostContract = oc
21
+ * .meta(authMeta({ required: true, scope: 'admin' }))
22
+ * .input(z.object({ postId: z.string() }))
23
+ * .output(z.object({ success: z.boolean() }))
24
+ *
25
+ * const authMiddleware = os.middleware(async ({ context, procedure, next }) => {
26
+ * const auth = getAuthMeta(procedure)
27
+ *
28
+ * if (auth?.required && !context.user) {
29
+ * throw new ORPCError('UNAUTHORIZED')
30
+ * }
31
+ *
32
+ * if (auth?.scope === 'admin' && !context.user?.isAdmin) {
33
+ * throw new ORPCError('FORBIDDEN')
34
+ * }
35
+ *
36
+ * return next()
37
+ * })
38
+ * ```
39
+ *
40
+ * @param name - Unique key for storing this meta entry.
41
+ * @param merge - Merges the existing value (or `undefined`) with the incoming value when applied multiple times.
42
+ *
43
+ * @returns A `[metaPlugin, getMeta]` tuple:
44
+ * - `metaPlugin(metadata)` - Attaches metadata to a procedure under `name`.
45
+ * - `getMeta(procedureOrLazy)` - Retrieves the metadata, or `undefined` if not set.
46
+ *
47
+ * @see {@link https://orpc.dev/docs/metadata | Metadata}
48
+ */
49
+ export declare function defineMeta<TName extends string, TData>(name: TName, merge: (incoming: TData, current: TData | undefined) => TData): [
50
+ metaPlugin: (meta: TData) => AnyMetaPlugin & {
51
+ name: TName;
52
+ },
53
+ getMeta: (procedureOrLazy: {
54
+ '~orpc': {
55
+ meta: Meta;
56
+ };
57
+ }) => TData | undefined
58
+ ];
@@ -0,0 +1,76 @@
1
+ import { toArray } from '@orpc/shared';
2
+ export function resolveMetaPlugins(baseMeta, existingPlugins, incomingPlugins) {
3
+ existingPlugins = toArray(existingPlugins);
4
+ incomingPlugins = toArray(incomingPlugins);
5
+ let meta = baseMeta;
6
+ for (const plugin of incomingPlugins) {
7
+ if (plugin.init) {
8
+ meta = plugin.init(meta);
9
+ }
10
+ }
11
+ const plugins = [...existingPlugins, ...incomingPlugins];
12
+ for (const plugin of plugins) {
13
+ if (plugin.apply) {
14
+ meta = plugin.apply(meta);
15
+ }
16
+ }
17
+ return [meta, plugins];
18
+ }
19
+ /**
20
+ * Quickly defines a meta plugin factory and reader.
21
+ *
22
+ * @example Mark a procedure as requiring authentication and read it in middleware.
23
+ * ```ts
24
+ * interface AuthMeta {
25
+ * required?: boolean
26
+ * scope?: 'user' | 'admin'
27
+ * }
28
+ *
29
+ * const [authMeta, getAuthMeta] = defineMeta(
30
+ * 'auth',
31
+ * (incoming: AuthMeta, current) => ({ ...current, ...incoming }),
32
+ * )
33
+ *
34
+ * const deletePostContract = oc
35
+ * .meta(authMeta({ required: true, scope: 'admin' }))
36
+ * .input(z.object({ postId: z.string() }))
37
+ * .output(z.object({ success: z.boolean() }))
38
+ *
39
+ * const authMiddleware = os.middleware(async ({ context, procedure, next }) => {
40
+ * const auth = getAuthMeta(procedure)
41
+ *
42
+ * if (auth?.required && !context.user) {
43
+ * throw new ORPCError('UNAUTHORIZED')
44
+ * }
45
+ *
46
+ * if (auth?.scope === 'admin' && !context.user?.isAdmin) {
47
+ * throw new ORPCError('FORBIDDEN')
48
+ * }
49
+ *
50
+ * return next()
51
+ * })
52
+ * ```
53
+ *
54
+ * @param name - Unique key for storing this meta entry.
55
+ * @param merge - Merges the existing value (or `undefined`) with the incoming value when applied multiple times.
56
+ *
57
+ * @returns A `[metaPlugin, getMeta]` tuple:
58
+ * - `metaPlugin(metadata)` - Attaches metadata to a procedure under `name`.
59
+ * - `getMeta(procedureOrLazy)` - Retrieves the metadata, or `undefined` if not set.
60
+ *
61
+ * @see {@link https://orpc.dev/docs/metadata | Metadata}
62
+ */
63
+ export function defineMeta(name, merge) {
64
+ const metaPlugin = (value) => ({
65
+ name,
66
+ init: (meta) => {
67
+ const current = meta[name];
68
+ return {
69
+ ...meta,
70
+ [name]: merge(value, current),
71
+ };
72
+ },
73
+ });
74
+ const getMeta = (procedureOrLazy) => procedureOrLazy['~orpc'].meta[name];
75
+ return [metaPlugin, getMeta];
76
+ }
package/dist/meta.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { ErrorMap } from './error.ts';
2
+ import type { AnySchema } from './schema.ts';
3
+ /**
4
+ * Arbitrary metadata attached to a procedure.
5
+ * Middleware, plugins, and tooling can read it later to control behavior.
6
+ *
7
+ * @see {@link https://orpc.dev/docs/metadata | Metadata}
8
+ */
9
+ export interface Meta {
10
+ [key: PropertyKey]: unknown;
11
+ }
12
+ export interface MetaPluginDefinition<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> {
13
+ __TInputSchema?: {
14
+ type: TInputSchema;
15
+ };
16
+ __TOutputSchema?: {
17
+ type: TOutputSchema;
18
+ };
19
+ __TErrorMap?: {
20
+ type: TErrorMap;
21
+ };
22
+ }
23
+ /**
24
+ * A metadata plugin passed to `.meta(...)`.
25
+ * Defines how metadata is initialized and merged, and can infer or restrict procedure types.
26
+ *
27
+ * @see {@link https://orpc.dev/docs/metadata | Metadata}
28
+ */
29
+ export interface MetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> {
30
+ /** This only for types, so it should be optional */
31
+ '~orpc'?: MetaPluginDefinition<TInputSchema, TOutputSchema, TErrorMap> | undefined;
32
+ /** Unique name of the plugin, used for identification. */
33
+ 'name': string;
34
+ /**
35
+ * Runs once when this plugin is first added to the builder.
36
+ * Use this to set up initial metadata values.
37
+ */
38
+ 'init'?: (meta: Meta) => Meta;
39
+ /**
40
+ * Runs every time metadata is updated.
41
+ * This is called for all plugins in the chain whenever a new plugin is added.
42
+ */
43
+ 'apply'?: (meta: Meta) => Meta;
44
+ }
45
+ /**
46
+ * A `MetaPlugin` with all type parameters relaxed to `any`.
47
+ *
48
+ * @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
49
+ * @see {@link https://orpc.dev/docs/procedure | Procedure}
50
+ */
51
+ export type AnyMetaPlugin = MetaPlugin<any, any, any>;
52
+ export declare function getHiddenMetaPlugins(container: unknown): AnyMetaPlugin[] | undefined;
53
+ export declare function setHiddenMetaPlugins<T extends object>(container: T, metaPlugins: AnyMetaPlugin[]): void;
package/dist/meta.js ADDED
@@ -0,0 +1,13 @@
1
+ import { isNonPrimitive } from '@orpc/shared';
2
+ const HIDDEN_META_PLUGINS_SYMBOL = /* @__PURE__ */ Symbol.for('ORPC_HIDDEN_META_PLUGINS');
3
+ export function getHiddenMetaPlugins(container) {
4
+ if (!isNonPrimitive(container)) {
5
+ return undefined;
6
+ }
7
+ return container[HIDDEN_META_PLUGINS_SYMBOL];
8
+ }
9
+ // oxlint-disable-next-line typescript/no-unnecessary-type-parameters
10
+ export function setHiddenMetaPlugins(container, metaPlugins) {
11
+ ;
12
+ container[HIDDEN_META_PLUGINS_SYMBOL] = metaPlugins;
13
+ }
@@ -0,0 +1,12 @@
1
+ export * from './request-validation.ts';
2
+ export {
3
+ /**
4
+ * @deprecated Use `RequestValidationLinkPlugin` instead.
5
+ */
6
+ RequestValidationLinkPlugin as RequestValidationPlugin, } from './request-validation.ts';
7
+ export * from './response-validation.ts';
8
+ export {
9
+ /**
10
+ * @deprecated Use `ResponseValidationLinkPlugin` instead.
11
+ */
12
+ ResponseValidationLinkPlugin as ResponseValidationPlugin, } from './response-validation.ts';
@@ -0,0 +1,12 @@
1
+ export * from './request-validation.js';
2
+ export {
3
+ /**
4
+ * @deprecated Use `RequestValidationLinkPlugin` instead.
5
+ */
6
+ RequestValidationLinkPlugin as RequestValidationPlugin, } from './request-validation.js';
7
+ export * from './response-validation.js';
8
+ export {
9
+ /**
10
+ * @deprecated Use `ResponseValidationLinkPlugin` instead.
11
+ */
12
+ ResponseValidationLinkPlugin as ResponseValidationPlugin, } from './response-validation.js';
@@ -0,0 +1,28 @@
1
+ import type { ClientContext } from '@orpc/client';
2
+ import type { StandardLinkOptions, StandardLinkPlugin } from '@orpc/client/standard';
3
+ import type { RouterContract } from '../router.ts';
4
+ export interface RequestValidationLinkPluginOptions<_T extends ClientContext> {
5
+ /**
6
+ * Forwards the locally validated/transformed input downstream.
7
+ *
8
+ * Disabled by default because some schema transforms produce a locally valid
9
+ * value that cannot be validated successfully again by the server.
10
+ * Keeping the original input as the flow input is the safer default.
11
+ *
12
+ * @default false
13
+ */
14
+ forwardValidatedInput?: boolean | undefined;
15
+ }
16
+ /**
17
+ * Validates client request input against contract schemas before the request is encoded.
18
+ * This is useful when your application relies on server-side validation.
19
+ *
20
+ * @see {@link https://orpc.dev/docs/plugins/request-validation | Request Validation Plugin}
21
+ */
22
+ export declare class RequestValidationLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
23
+ private readonly contract;
24
+ name: string;
25
+ private readonly forwardValidatedInput;
26
+ constructor(contract: RouterContract, options?: RequestValidationLinkPluginOptions<T>);
27
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
28
+ }
@@ -0,0 +1,55 @@
1
+ import { ORPCError } from '@orpc/client';
2
+ import { mergeTwoLevels, toArray } from '@orpc/shared';
3
+ import { ValidationError } from '../error.js';
4
+ import { getProcedureContractOrThrow } from '../router-utils.js';
5
+ /**
6
+ * Validates client request input against contract schemas before the request is encoded.
7
+ * This is useful when your application relies on server-side validation.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/plugins/request-validation | Request Validation Plugin}
10
+ */
11
+ export class RequestValidationLinkPlugin {
12
+ contract;
13
+ name = '~request-validation';
14
+ forwardValidatedInput;
15
+ constructor(contract, options = {}) {
16
+ this.contract = contract;
17
+ this.forwardValidatedInput = options.forwardValidatedInput ?? false;
18
+ }
19
+ init(options) {
20
+ return {
21
+ ...options,
22
+ interceptors: [
23
+ ...toArray(options.interceptors),
24
+ async ({ next, ...interceptorOptions }) => {
25
+ const procedure = getProcedureContractOrThrow(this.contract, interceptorOptions.path);
26
+ const inputSchemas = toArray(procedure['~orpc'].inputSchemas);
27
+ const originalInput = interceptorOptions.input;
28
+ let currentInput = originalInput;
29
+ for (const [index, schema] of inputSchemas.entries()) {
30
+ // Mirrors the server's stacked input validation.
31
+ const validating = index !== 0 ? mergeTwoLevels(originalInput, currentInput) : currentInput;
32
+ const result = await schema['~standard'].validate(validating);
33
+ if (result.issues) {
34
+ throw new ORPCError('BAD_REQUEST', {
35
+ message: 'Input validation failed',
36
+ data: {
37
+ issues: result.issues,
38
+ },
39
+ cause: new ValidationError({
40
+ message: 'Input validation failed',
41
+ issues: result.issues,
42
+ invalidData: validating,
43
+ }),
44
+ });
45
+ }
46
+ currentInput = index !== 0 ? mergeTwoLevels(currentInput, result.value) : result.value;
47
+ }
48
+ return this.forwardValidatedInput
49
+ ? next({ ...interceptorOptions, input: currentInput })
50
+ : next();
51
+ },
52
+ ],
53
+ };
54
+ }
55
+ }
@@ -0,0 +1,15 @@
1
+ import type { ClientContext } from '@orpc/client';
2
+ import type { StandardLinkOptions, StandardLinkPlugin } from '@orpc/client/standard';
3
+ import type { RouterContract } from '../router.ts';
4
+ /**
5
+ * Validates server responses against contract schemas before your application uses them.
6
+ * This helps ensure the data returned by the server matches the types defined in your contract.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/plugins/response-validation | Response Validation Plugin}
9
+ */
10
+ export declare class ResponseValidationLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
11
+ private readonly contract;
12
+ name: string;
13
+ constructor(contract: RouterContract);
14
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
15
+ }
@@ -0,0 +1,72 @@
1
+ import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from '@orpc/client';
2
+ import { isAsyncIteratorObject, override, toArray } from '@orpc/shared';
3
+ import { reconcileORPCError } from '../error-utils.js';
4
+ import { ValidationError } from '../error.js';
5
+ import { getProcedureContractOrThrow } from '../router-utils.js';
6
+ /**
7
+ * Validates server responses against contract schemas before your application uses them.
8
+ * This helps ensure the data returned by the server matches the types defined in your contract.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/plugins/response-validation | Response Validation Plugin}
11
+ */
12
+ export class ResponseValidationLinkPlugin {
13
+ contract;
14
+ name = '~response-validation';
15
+ constructor(contract) {
16
+ this.contract = contract;
17
+ }
18
+ init(options) {
19
+ return {
20
+ ...options,
21
+ interceptors: [
22
+ async ({ next, path }) => {
23
+ const procedure = getProcedureContractOrThrow(this.contract, path);
24
+ const reconcileError = async (error) => {
25
+ if (error instanceof ORPCError) {
26
+ return await reconcileORPCError(procedure['~orpc'].errorMap, error);
27
+ }
28
+ return error;
29
+ };
30
+ try {
31
+ const output = await next();
32
+ if (isAsyncIteratorObject(output)) {
33
+ /**
34
+ * Errors thrown while consuming the iterator must be reconciled too.
35
+ *
36
+ * @warning
37
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
38
+ */
39
+ return override(output, wrapAsyncIteratorPreservingEventMeta(output, { mapError: reconcileError }));
40
+ }
41
+ return output;
42
+ }
43
+ catch (error) {
44
+ throw await reconcileError(error);
45
+ }
46
+ },
47
+ ...toArray(options.interceptors),
48
+ async ({ next, path }) => {
49
+ const procedure = getProcedureContractOrThrow(this.contract, path);
50
+ const outputSchemas = toArray(procedure['~orpc'].outputSchemas);
51
+ let output = await next();
52
+ for (let i = outputSchemas.length - 1; i >= 0; i--) {
53
+ const schema = outputSchemas[i];
54
+ const result = await schema['~standard'].validate(output);
55
+ if (result.issues) {
56
+ throw new ORPCError('INTERNAL_SERVER_ERROR', {
57
+ message: 'Output validation failed',
58
+ cause: new ValidationError({
59
+ message: 'Output validation failed',
60
+ issues: result.issues,
61
+ invalidData: output,
62
+ }),
63
+ });
64
+ }
65
+ output = result.value;
66
+ }
67
+ return output;
68
+ },
69
+ ],
70
+ };
71
+ }
72
+ }
@@ -0,0 +1,5 @@
1
+ import type { Client, ClientContext } from '@orpc/client';
2
+ import type { ThrowableError } from '@orpc/shared';
3
+ import type { ErrorMap, ORPCErrorFromErrorMap } from './error.ts';
4
+ import type { AnySchema, InferSchemaInput, InferSchemaOutput } from './schema.ts';
5
+ export type ProcedureContractClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ORPCErrorFromErrorMap<TErrorMap> | ThrowableError>;