@orpc/contract 2.0.0-beta.5 → 2.0.0-beta.50

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 (46) hide show
  1. package/README.md +137 -102
  2. package/dist/builder-variants.d.ts +103 -0
  3. package/dist/builder.d.ts +78 -0
  4. package/dist/builder.js +108 -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 +77 -0
  8. package/dist/error-factory.js +109 -0
  9. package/dist/error-utils.d.ts +5 -0
  10. package/dist/error-utils.js +37 -0
  11. package/dist/error.d.ts +41 -0
  12. package/dist/error.js +22 -0
  13. package/dist/index.d.ts +20 -182
  14. package/dist/index.js +12 -0
  15. package/dist/meta-built-in.d.ts +30 -0
  16. package/dist/meta-built-in.js +45 -0
  17. package/dist/meta-utils.d.ts +55 -0
  18. package/dist/meta-utils.js +70 -0
  19. package/dist/meta.d.ts +53 -0
  20. package/dist/meta.js +11 -0
  21. package/dist/plugins/index.d.ts +3 -38
  22. package/dist/plugins/index.js +2 -0
  23. package/dist/plugins/request-validation.d.ts +28 -0
  24. package/dist/plugins/request-validation.js +50 -0
  25. package/dist/plugins/response-validation.d.ts +15 -0
  26. package/dist/plugins/response-validation.js +67 -0
  27. package/dist/procedure-client.d.ts +5 -0
  28. package/dist/procedure.d.ts +28 -0
  29. package/dist/procedure.js +17 -0
  30. package/dist/router-client.d.ts +11 -0
  31. package/dist/router-utils.d.ts +23 -0
  32. package/dist/router-utils.js +59 -0
  33. package/dist/router.d.ts +42 -0
  34. package/dist/schema-built-in.d.ts +18 -0
  35. package/dist/schema-built-in.js +69 -0
  36. package/dist/schema-utils.d.ts +20 -0
  37. package/dist/schema-utils.js +36 -0
  38. package/dist/schema.d.ts +25 -0
  39. package/package.json +34 -24
  40. package/dist/index.d.mts +0 -182
  41. package/dist/index.mjs +0 -193
  42. package/dist/plugins/index.d.mts +0 -38
  43. package/dist/plugins/index.mjs +0 -90
  44. package/dist/shared/contract.CW-2wl1i.mjs +0 -180
  45. package/dist/shared/contract.Do92aRJ4.d.mts +0 -126
  46. package/dist/shared/contract.Do92aRJ4.d.ts +0 -126
package/dist/index.d.ts CHANGED
@@ -1,182 +1,20 @@
1
- import { E as ErrorMap, A as AnySchema, P as ProcedureContract, M as MetaPlugin, a as MergedSchema, b as Meta, c as AnyMetaPlugin, R as RouterContract, d as AnyProcedureContract, S as Schema, I as InferSchemaInput, e as InferSchemaOutput, O as ORPCErrorFromErrorMap, f as SchemaIssue } from './shared/contract.Do92aRJ4.js';
2
- export { g as ErrorMapItem, H as HIDDEN_META_PLUGINS_SYMBOL, h as InferRouterContractError, i as InferRouterContractErrorMap, j as InferRouterContractErrors, k as InferRouterContractInputs, l as InferRouterContractOutputs, m as MetaPluginDefinition, n as ProcedureContractDefinition, V as ValidationError, o as ValidationErrorOptions, p as getHiddenMetaPlugins, s as setHiddenMetaPlugins } from './shared/contract.Do92aRJ4.js';
3
- import { AnyORPCError, ClientContext, Client, ClientRest, ThrowableError as ThrowableError$1, ORPCClientOptions, ClientLink } from '@orpc/client';
4
- export { Client, ClientContext, ClientOptions, ClientRest, FriendlyClientOptions } from '@orpc/client';
5
- import { ThrowableError, PromiseWithError, AsyncIteratorClass, Promisable, IsEqual } from '@orpc/shared';
6
- export { PromiseWithError, Registry, ThrowableError } from '@orpc/shared';
7
- import '@standard-schema/spec';
8
-
9
- type MergedErrorMap<T1 extends ErrorMap, T2 extends ErrorMap> = keyof T1 extends never | keyof T2 ? T2 : Omit<T1, keyof T2> & T2;
10
- declare function mergeErrorMap<T1 extends ErrorMap = object, T2 extends ErrorMap = object>(errorMap1: T1 | undefined, errorMap2: T2 | undefined): MergedErrorMap<T1, T2>;
11
- declare function reconcileORPCError(map: ErrorMap, error: AnyORPCError): Promise<AnyORPCError>;
12
-
13
- interface ProcedureContractBuilderWithInput<TInputSchema extends AnySchema, TErrorMap extends ErrorMap> extends ProcedureContract<TInputSchema, InitialOutputSchema, TErrorMap> {
14
- meta(...plugins: MetaPlugin<TInputSchema, InitialOutputSchema, TErrorMap>[]): ProcedureContractBuilderWithInput<TInputSchema, TErrorMap>;
15
- errors<T extends ErrorMap>(errors: T): ProcedureContractBuilderWithInput<TInputSchema, MergedErrorMap<TErrorMap, T>>;
16
- input<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInput<MergedSchema<T, TInputSchema>, TErrorMap>;
17
- output<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInputOutput<TInputSchema, T, TErrorMap>;
18
- }
19
- interface ProcedureContractBuilderWithOutput<TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends ProcedureContract<InitialInputSchema, TOutputSchema, TErrorMap> {
20
- meta(...plugins: MetaPlugin<InitialInputSchema, TOutputSchema, TErrorMap>[]): ProcedureContractBuilderWithOutput<TOutputSchema, TErrorMap>;
21
- errors<T extends ErrorMap>(errors: T): ProcedureContractBuilderWithOutput<TOutputSchema, MergedErrorMap<TErrorMap, T>>;
22
- input<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInputOutput<T, TOutputSchema, TErrorMap>;
23
- output<T extends AnySchema>(schema: T): ProcedureContractBuilderWithOutput<MergedSchema<T, TOutputSchema>, TErrorMap>;
24
- }
25
- interface ProcedureContractBuilderWithInputOutput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends ProcedureContract<TInputSchema, TOutputSchema, TErrorMap> {
26
- meta(...plugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[]): ProcedureContractBuilderWithInputOutput<TInputSchema, TOutputSchema, TErrorMap>;
27
- errors<T extends ErrorMap>(errors: T): ProcedureContractBuilderWithInputOutput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, T>>;
28
- input<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInputOutput<MergedSchema<T, TInputSchema>, TOutputSchema, TErrorMap>;
29
- output<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInputOutput<TInputSchema, MergedSchema<T, TOutputSchema>, TErrorMap>;
30
- }
31
-
32
- type AugmentedContractRouter<T extends RouterContract, TErrorMap extends ErrorMap> = T extends ProcedureContract<infer $InputSchema, infer $OutputSchema, infer $Errors> ? ProcedureContract<$InputSchema, $OutputSchema, MergedErrorMap<TErrorMap, $Errors>> : {
33
- [K in keyof T]: T[K] extends RouterContract ? AugmentedContractRouter<T[K], TErrorMap> : never;
34
- };
35
- interface AugmentContractRouterOptions<TErrorMap extends ErrorMap> {
36
- meta: Meta;
37
- metaPlugins?: AnyMetaPlugin[] | undefined;
38
- errorMap: TErrorMap;
39
- }
40
- /**
41
- * Add capabilities without changing identity of the router contract
42
- */
43
- declare function augmentContractRouter<T extends RouterContract, TErrorMap extends ErrorMap>(router: T, options: AugmentContractRouterOptions<TErrorMap>): AugmentedContractRouter<T, TErrorMap>;
44
- declare function getRouterContract(router: RouterContract, path: readonly string[]): RouterContract | undefined;
45
- declare function getProcedureContractOrThrow(router: RouterContract, path: readonly string[]): AnyProcedureContract;
46
- declare function minifyRouterContract(router: RouterContract): RouterContract;
47
-
48
- type InitialInputSchema = Schema<void, unknown>;
49
- type InitialOutputSchema = Schema<unknown>;
50
- declare class ContractBuilder<TErrorMap extends ErrorMap> extends ProcedureContract<InitialInputSchema, InitialOutputSchema, TErrorMap> {
51
- /**
52
- * Private constructor to prevent direct instantiation.
53
- * Use the static `create` method to initialize a new instance with a safe initial definition.
54
- */
55
- private constructor();
56
- static create(): ContractBuilder<object>;
57
- meta(...plugins: MetaPlugin<InitialInputSchema, InitialOutputSchema, TErrorMap>[]): ContractBuilder<TErrorMap>;
58
- errors<T extends ErrorMap>(errors: T): ContractBuilder<MergedErrorMap<TErrorMap, T>>;
59
- input<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInput<T, TErrorMap>;
60
- output<T extends AnySchema>(schema: T): ProcedureContractBuilderWithOutput<T, TErrorMap>;
61
- router<T extends RouterContract>(router: T): AugmentedContractRouter<T, TErrorMap>;
62
- }
63
- declare const oc: ContractBuilder<object>;
64
-
65
- type ProcedureContractClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ORPCErrorFromErrorMap<TErrorMap> | ThrowableError>;
66
-
67
- type RouterContractClient<TRouter extends RouterContract, TClientContext extends ClientContext = object> = TRouter extends ProcedureContract<infer UInputSchema, infer UOutputSchema, infer UErrorMap> ? ProcedureContractClient<TClientContext, UInputSchema, UOutputSchema, UErrorMap> : {
68
- [K in keyof TRouter]: TRouter[K] extends RouterContract ? RouterContractClient<TRouter[K], TClientContext> : never;
69
- };
70
-
71
- interface ContractCaller<TClientContext extends ClientContext> {
72
- <TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(procedure: ProcedureContract<TInputSchema, TOutputSchema, TErrorMap>, ...rest: ClientRest<TClientContext, InferSchemaInput<TInputSchema>>): PromiseWithError<InferSchemaOutput<TOutputSchema>, ORPCErrorFromErrorMap<TErrorMap> | ThrowableError$1>;
73
- }
74
- interface ContractCallerOptions<TClientContext extends ClientContext> extends Pick<ORPCClientOptions<RouterContractClient<RouterContract, TClientContext>>, 'interceptors' | 'scoped'> {
75
- /**
76
- * An optional reference to the root router-contract.
77
- * When provided, the caller will automatically register the called procedure-contract
78
- * into the router at the path defined by `meta.path`.
79
- */
80
- contractRef?: undefined | RouterContract;
81
- }
82
- declare function createContractCaller<TClientContext extends ClientContext>(link: ClientLink<TClientContext>, options?: ContractCallerOptions<TClientContext>): ContractCaller<TClientContext>;
83
-
84
- interface EventIteratorSchemaDetails {
85
- yieldSchema: AnySchema;
86
- returnSchema?: AnySchema;
87
- }
88
- /**
89
- * Define schema for an event iterator.
90
- *
91
- * @see {@link https://orpc.dev/docs/event-iterator#validate-event-iterator Validate Event Iterator Docs}
92
- */
93
- declare function eventIterator<TYieldIn, TYieldOut, TReturnIn = unknown, TReturnOut = unknown>(yieldSchema: Schema<TYieldIn, TYieldOut>, returnSchema?: Schema<TReturnIn, TReturnOut>): Schema<AsyncIteratorObject<TYieldIn, TReturnIn, void>, AsyncIteratorClass<TYieldOut, TReturnOut, void>>;
94
- declare function getEventIteratorSchemaDetails(schema: AnySchema | undefined): undefined | EventIteratorSchemaDetails;
95
-
96
- interface PathMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
97
- name: '~path';
98
- }
99
- declare const meta: {
100
- path<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(path: string[]): PathMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
101
- };
102
- declare function getPathMeta(procedureOrLazy: {
103
- '~orpc': {
104
- meta: Meta;
105
- };
106
- }): string[] | undefined;
107
-
108
- 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>[]];
109
- /**
110
- * Quickly defines a meta plugin factory and reader.
111
- *
112
- * @example Mark a procedure as requiring authentication and read it in middleware.
113
- * ```ts
114
- * interface AuthMeta {
115
- * required?: boolean
116
- * scope?: 'user' | 'admin'
117
- * }
118
- *
119
- * const [authMeta, getAuthMeta] = defineMeta(
120
- * 'auth',
121
- * (incoming: AuthMeta, current) => ({ ...current, ...incoming }),
122
- * )
123
- *
124
- * const deletePostContract = oc
125
- * .meta(authMeta({ required: true, scope: 'admin' }))
126
- * .input(z.object({ postId: z.string() }))
127
- * .output(z.object({ success: z.boolean() }))
128
- *
129
- * const authMiddleware = os.middleware(async ({ context, procedure, next }) => {
130
- * const auth = getAuthMeta(procedure)
131
- *
132
- * if (auth?.required && !context.user) {
133
- * throw new ORPCError('UNAUTHORIZED')
134
- * }
135
- *
136
- * if (auth?.scope === 'admin' && !context.user?.isAdmin) {
137
- * throw new ORPCError('FORBIDDEN')
138
- * }
139
- *
140
- * return next()
141
- * })
142
- * ```
143
- *
144
- * @param name - Unique key for storing this meta entry.
145
- * @param merge - Merges the existing value (or `undefined`) with the incoming value when applied multiple times.
146
- *
147
- * @returns A `[metaPlugin, getMeta]` tuple:
148
- * - `metaPlugin(metadata)` - Attaches metadata to a procedure under `name`.
149
- * - `getMeta(procedureOrLazy)` - Retrieves the metadata, or `undefined` if not set.
150
- */
151
- declare function defineMeta<TName extends string, TData>(name: TName, merge: (incoming: TData, current: TData | undefined) => TData): [
152
- metaPlugin: (meta: TData) => AnyMetaPlugin & {
153
- name: TName;
154
- },
155
- getMeta: (procedureOrLazy: {
156
- '~orpc': {
157
- meta: Meta;
158
- };
159
- }) => TData | undefined
160
- ];
161
-
162
- type TypeRest<TInput, TOutput> = [map: (input: TInput) => Promisable<TOutput>] | (IsEqual<TInput, TOutput> extends true ? [] : never);
163
- /**
164
- * Create a schema for things can be trust without validation.
165
- * You can optionally pass a map function for mapping
166
- *
167
- * @example
168
- * ```ts
169
- * const normal = type<number>()
170
- * const withMap = type<number, string>(input => input.toString())
171
- *```
172
- *
173
- * @see {@link https://orpc.dev/docs/procedure#type-utility Type Utility Docs}
174
- */
175
- declare function type<TInput, TOutput = TInput>(...[map]: TypeRest<TInput, TOutput>): Schema<TInput, TOutput>;
176
- /**
177
- * Check if the given issue is following the standard-schema issue format.
178
- */
179
- declare function isSchemaIssue(issue: unknown): issue is SchemaIssue;
180
-
181
- export { AnyMetaPlugin, AnyProcedureContract, AnySchema, ContractBuilder, ErrorMap, InferSchemaInput, InferSchemaOutput, MergedSchema, Meta, MetaPlugin, ORPCErrorFromErrorMap, ProcedureContract, RouterContract, Schema, SchemaIssue, augmentContractRouter, createContractCaller, defineMeta, eventIterator, getEventIteratorSchemaDetails, getPathMeta, getProcedureContractOrThrow, getRouterContract, isSchemaIssue, mergeErrorMap, meta, minifyRouterContract, oc, reconcileORPCError, resolveMetaPlugins, type };
182
- export type { AugmentContractRouterOptions, AugmentedContractRouter, ContractCaller, ContractCallerOptions, EventIteratorSchemaDetails, InitialInputSchema, InitialOutputSchema, MergedErrorMap, PathMetaPlugin, ProcedureContractBuilderWithInput, ProcedureContractBuilderWithInputOutput, ProcedureContractBuilderWithOutput, ProcedureContractClient, RouterContractClient, TypeRest };
1
+ import { ContractBuilder, InitialInputSchema, InitialOutputSchema, oc } from "./builder.js";
2
+ import { ProcedureContractBuilderWithInput, ProcedureContractBuilderWithInputOutput, ProcedureContractBuilderWithOutput } from "./builder-variants.js";
3
+ import { ContractClientFactory, ContractClientFactoryOptions, createContractClientFactory } from "./client-factory.js";
4
+ import { ErrorMap, ErrorMapItem, ORPCErrorFromErrorMap, ValidationError, ValidationErrorOptions } from "./error.js";
5
+ import { ORPCErrorConstructorMap, ORPCErrorConstructorMapItem, ORPCErrorConstructorMapItemOptions, ORPCErrorFactory, ORPCErrorFactoryOptions, createORPCErrorConstructorMap, error } from "./error-factory.js";
6
+ import { MergedErrorMap, mergeErrorMap, reconcileORPCError } from "./error-utils.js";
7
+ import { AnyMetaPlugin, Meta, MetaPlugin, MetaPluginDefinition, getHiddenMetaPlugins, setHiddenMetaPlugins } from "./meta.js";
8
+ import { PathMetaPlugin, getPathMeta, meta, resolveBasePathMeta } from "./meta-built-in.js";
9
+ import { defineMeta, resolveMetaPlugins } from "./meta-utils.js";
10
+ import { AnyProcedureContract, ProcedureContract, ProcedureContractDefinition } from "./procedure.js";
11
+ import { ProcedureContractClient } from "./procedure-client.js";
12
+ import { InferRouterContractError, InferRouterContractErrorMap, InferRouterContractErrors, InferRouterContractInputs, InferRouterContractOutputs, RouterContract } from "./router.js";
13
+ import { RouterContractClient } from "./router-client.js";
14
+ import { AugmentContractRouterOptions, AugmentedContractRouter, getProcedureContractOrThrow, getRouterContract, minifyRouterContract } from "./router-utils.js";
15
+ import { AnySchema, InferSchemaInput, InferSchemaOutput, MergedSchema, Schema, SchemaIssue } from "./schema.js";
16
+ import { AsyncIteratorObjectSchemasDetails, asyncIteratorObject, getAsyncIteratorObjectSchemasDetails } from "./schema-built-in.js";
17
+ import { TypeRest, isSchemaIssue, type } from "./schema-utils.js";
18
+ import { AsyncIteratorClass, PromiseWithError, Registry, ThrowableError } from "@orpc/shared";
19
+ import { Client, ClientContext, ClientOptions, ClientRest, FriendlyClientOptions } from "@orpc/client";
20
+ export { type AnyProcedureContract as AnyContractProcedure, type RouterContract as AnyContractRouter, AnyMetaPlugin, AnyProcedureContract, AnySchema, type AsyncIteratorClass, type AsyncIteratorObjectSchemasDetails, type AugmentContractRouterOptions, type AugmentedContractRouter, type Client, type ClientContext, type ClientOptions, type ClientRest, ContractBuilder, ContractClientFactory, ContractClientFactoryOptions, type RouterContractClient as ContractRouterClient, ErrorMap, ErrorMapItem, type FriendlyClientOptions, type InferRouterContractErrorMap as InferContractRouterErrorMap, type InferRouterContractInputs as InferContractRouterInputs, type InferRouterContractOutputs as InferContractRouterOutputs, InferRouterContractError, InferRouterContractErrorMap, InferRouterContractErrors, InferRouterContractInputs, InferRouterContractOutputs, InferSchemaInput, InferSchemaOutput, InitialInputSchema, InitialOutputSchema, MergedErrorMap, MergedSchema, Meta, MetaPlugin, MetaPluginDefinition, ORPCErrorConstructorMap, ORPCErrorConstructorMapItem, ORPCErrorConstructorMapItemOptions, ORPCErrorFactory, ORPCErrorFactoryOptions, ORPCErrorFromErrorMap, PathMetaPlugin, ProcedureContract, ProcedureContractBuilderWithInput, ProcedureContractBuilderWithInputOutput, ProcedureContractBuilderWithOutput, ProcedureContractClient, ProcedureContractDefinition, type PromiseWithError, type Registry, RouterContract, RouterContractClient, Schema, SchemaIssue, type ThrowableError, TypeRest, ValidationError, ValidationErrorOptions, asyncIteratorObject, createContractClientFactory, createORPCErrorConstructorMap, defineMeta, error, asyncIteratorObject as eventIterator, getAsyncIteratorObjectSchemasDetails, getRouterContract as getContractRouter, getHiddenMetaPlugins, getPathMeta, getProcedureContractOrThrow, getRouterContract, isSchemaIssue, mergeErrorMap, meta, minifyRouterContract as minifyContractRouter, minifyRouterContract, oc, reconcileORPCError, resolveBasePathMeta, resolveMetaPlugins, setHiddenMetaPlugins, type };
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { ContractBuilder, oc } from "./builder.js";
2
+ export { createContractClientFactory } from "./client-factory.js";
3
+ export { ValidationError } from "./error.js";
4
+ export { createORPCErrorConstructorMap, error } from "./error-factory.js";
5
+ export { mergeErrorMap, reconcileORPCError } from "./error-utils.js";
6
+ export { getHiddenMetaPlugins, setHiddenMetaPlugins } from "./meta.js";
7
+ export { getPathMeta, meta, resolveBasePathMeta } from "./meta-built-in.js";
8
+ export { defineMeta, resolveMetaPlugins } from "./meta-utils.js";
9
+ export { ProcedureContract } from "./procedure.js";
10
+ export { getProcedureContractOrThrow, getRouterContract as getContractRouter, getRouterContract, minifyRouterContract as minifyContractRouter, minifyRouterContract } from "./router-utils.js";
11
+ export { asyncIteratorObject, asyncIteratorObject as eventIterator, getAsyncIteratorObjectSchemasDetails } from "./schema-built-in.js";
12
+ export { isSchemaIssue, type } from "./schema-utils.js";
@@ -0,0 +1,30 @@
1
+ import { ErrorMap } from "./error.js";
2
+ import { Meta, MetaPlugin } from "./meta.js";
3
+ import { RouterContract } from "./router.js";
4
+ import { AnySchema } from "./schema.js";
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,45 @@
1
+ import { ProcedureContract } from "./procedure.js";
2
+ import { isNonPrimitive } from "@orpc/shared";
3
+ // src/meta-built-in.ts
4
+ /**
5
+ * Built-in metadata plugins.
6
+ * `meta.path` records a procedure contract's path inside the root contract,
7
+ * which is required for the contract client factory pattern.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
10
+ */
11
+ const meta = { path(path) {
12
+ return {
13
+ name: "~path",
14
+ init(meta) {
15
+ return {
16
+ ...meta,
17
+ "~path": path
18
+ };
19
+ }
20
+ };
21
+ } };
22
+ function getPathMeta(procedureOrLazy) {
23
+ return procedureOrLazy["~orpc"].meta["~path"];
24
+ }
25
+ /**
26
+ * Resolve the base path of a contract from the first procedure-contract
27
+ * that defines `meta.path`: its `meta.path` minus its path inside the given contract.
28
+ * For a procedure-contract, this is its `meta.path` itself.
29
+ *
30
+ * Returns `undefined` when no procedure-contract defines `meta.path`.
31
+ */
32
+ function resolveBasePathMeta(contract, currentPath = []) {
33
+ if (contract instanceof ProcedureContract) {
34
+ const path = getPathMeta(contract);
35
+ if (!path) return;
36
+ const base = path.slice(0, Math.max(0, path.length - currentPath.length));
37
+ if (currentPath.some((key, i) => path[base.length + i] !== key)) throw new TypeError(`Procedure contract at "${currentPath.join(".")}" defines meta.path "${path.join(".")}" that does not match its path inside the given router contract.`);
38
+ return base;
39
+ }
40
+ if (isNonPrimitive(contract)) for (const [key, child] of Object.entries(contract)) {
41
+ const base = resolveBasePathMeta(child, [...currentPath, key]);
42
+ if (base !== void 0) return base;
43
+ }
44
+ }
45
+ export { getPathMeta, meta, resolveBasePathMeta };
@@ -0,0 +1,55 @@
1
+ import { ErrorMap } from "./error.js";
2
+ import { AnyMetaPlugin, Meta, MetaPlugin } from "./meta.js";
3
+ import { AnySchema } from "./schema.js";
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): [metaPlugin: (meta: TData) => AnyMetaPlugin & {
50
+ name: TName;
51
+ }, getMeta: (procedureOrLazy: {
52
+ "~orpc": {
53
+ meta: Meta;
54
+ };
55
+ }) => TData | undefined];
@@ -0,0 +1,70 @@
1
+ import { toArray } from "@orpc/shared";
2
+ // src/meta-utils.ts
3
+ function resolveMetaPlugins(baseMeta, existingPlugins, incomingPlugins) {
4
+ existingPlugins = toArray(existingPlugins);
5
+ incomingPlugins = toArray(incomingPlugins);
6
+ let meta = baseMeta;
7
+ for (const plugin of incomingPlugins) if (plugin.init) meta = plugin.init(meta);
8
+ const plugins = [...existingPlugins, ...incomingPlugins];
9
+ for (const plugin of plugins) if (plugin.apply) meta = plugin.apply(meta);
10
+ return [meta, plugins];
11
+ }
12
+ /**
13
+ * Quickly defines a meta plugin factory and reader.
14
+ *
15
+ * @example Mark a procedure as requiring authentication and read it in middleware.
16
+ * ```ts
17
+ * interface AuthMeta {
18
+ * required?: boolean
19
+ * scope?: 'user' | 'admin'
20
+ * }
21
+ *
22
+ * const [authMeta, getAuthMeta] = defineMeta(
23
+ * 'auth',
24
+ * (incoming: AuthMeta, current) => ({ ...current, ...incoming }),
25
+ * )
26
+ *
27
+ * const deletePostContract = oc
28
+ * .meta(authMeta({ required: true, scope: 'admin' }))
29
+ * .input(z.object({ postId: z.string() }))
30
+ * .output(z.object({ success: z.boolean() }))
31
+ *
32
+ * const authMiddleware = os.middleware(async ({ context, procedure, next }) => {
33
+ * const auth = getAuthMeta(procedure)
34
+ *
35
+ * if (auth?.required && !context.user) {
36
+ * throw new ORPCError('UNAUTHORIZED')
37
+ * }
38
+ *
39
+ * if (auth?.scope === 'admin' && !context.user?.isAdmin) {
40
+ * throw new ORPCError('FORBIDDEN')
41
+ * }
42
+ *
43
+ * return next()
44
+ * })
45
+ * ```
46
+ *
47
+ * @param name - Unique key for storing this meta entry.
48
+ * @param merge - Merges the existing value (or `undefined`) with the incoming value when applied multiple times.
49
+ *
50
+ * @returns A `[metaPlugin, getMeta]` tuple:
51
+ * - `metaPlugin(metadata)` - Attaches metadata to a procedure under `name`.
52
+ * - `getMeta(procedureOrLazy)` - Retrieves the metadata, or `undefined` if not set.
53
+ *
54
+ * @see {@link https://orpc.dev/docs/metadata | Metadata}
55
+ */
56
+ function defineMeta(name, merge) {
57
+ const metaPlugin = (value) => ({
58
+ name,
59
+ init: (meta) => {
60
+ const current = meta[name];
61
+ return {
62
+ ...meta,
63
+ [name]: merge(value, current)
64
+ };
65
+ }
66
+ });
67
+ const getMeta = (procedureOrLazy) => procedureOrLazy["~orpc"].meta[name];
68
+ return [metaPlugin, getMeta];
69
+ }
70
+ export { defineMeta, resolveMetaPlugins };
package/dist/meta.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { ErrorMap } from "./error.js";
2
+ import { AnySchema } from "./schema.js";
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,11 @@
1
+ import { isNonPrimitive } from "@orpc/shared";
2
+ // src/meta.ts
3
+ const HIDDEN_META_PLUGINS_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_HIDDEN_META_PLUGINS");
4
+ function getHiddenMetaPlugins(container) {
5
+ if (!isNonPrimitive(container)) return;
6
+ return container[HIDDEN_META_PLUGINS_SYMBOL];
7
+ }
8
+ function setHiddenMetaPlugins(container, metaPlugins) {
9
+ container[HIDDEN_META_PLUGINS_SYMBOL] = metaPlugins;
10
+ }
11
+ export { getHiddenMetaPlugins, setHiddenMetaPlugins };
@@ -1,38 +1,3 @@
1
- import { ClientContext } from '@orpc/client';
2
- import { StandardLinkPlugin, StandardLinkOptions } from '@orpc/client/standard';
3
- import { R as RouterContract } from '../shared/contract.Do92aRJ4.js';
4
- import '@orpc/shared';
5
- import '@standard-schema/spec';
6
-
7
- interface RequestValidationLinkPluginOptions<_T extends ClientContext> {
8
- /**
9
- * Forwards the locally validated/transformed input downstream.
10
- *
11
- * Disabled by default because some schema transforms produce a locally valid
12
- * value that cannot be validated successfully again by the server.
13
- * Keeping the original input as the flow input is the safer default.
14
- *
15
- * @default false
16
- */
17
- forwardValidatedInput?: boolean | undefined;
18
- }
19
- /**
20
- * Validates client request input against contract schemas before the request is encoded.
21
- */
22
- 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
- }
29
-
30
- declare class ResponseValidationLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
31
- private readonly contract;
32
- name: string;
33
- constructor(contract: RouterContract);
34
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
35
- }
36
-
37
- export { RequestValidationLinkPlugin, ResponseValidationLinkPlugin };
38
- export type { RequestValidationLinkPluginOptions };
1
+ import { RequestValidationLinkPlugin, RequestValidationLinkPluginOptions } from "./request-validation.js";
2
+ import { ResponseValidationLinkPlugin } from "./response-validation.js";
3
+ export { RequestValidationLinkPlugin, RequestValidationLinkPluginOptions, RequestValidationLinkPlugin as RequestValidationPlugin, ResponseValidationLinkPlugin, ResponseValidationLinkPlugin as ResponseValidationPlugin };
@@ -0,0 +1,2 @@
1
+ export { RequestValidationLinkPlugin, RequestValidationLinkPlugin as RequestValidationPlugin } from "./request-validation.js";
2
+ export { ResponseValidationLinkPlugin, ResponseValidationLinkPlugin as ResponseValidationPlugin } from "./response-validation.js";
@@ -0,0 +1,28 @@
1
+ import { RouterContract } from "../router.js";
2
+ import { ClientContext } from "@orpc/client";
3
+ import { StandardLinkOptions, StandardLinkPlugin } from "@orpc/client/standard";
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,50 @@
1
+ import { ValidationError } from "../error.js";
2
+ import { getProcedureContractOrThrow } from "../router-utils.js";
3
+ import { mergeTwoLevels, toArray } from "@orpc/shared";
4
+ import { ORPCError } from "@orpc/client";
5
+ // src/plugins/request-validation.ts
6
+ /**
7
+ * Validates client request input against contract schemas before the request is encoded.
8
+ * This is useful when your application relies on server-side validation.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/plugins/request-validation | Request Validation Plugin}
11
+ */
12
+ var RequestValidationLinkPlugin = class {
13
+ contract;
14
+ name = "~request-validation";
15
+ forwardValidatedInput;
16
+ constructor(contract, options = {}) {
17
+ this.contract = contract;
18
+ this.forwardValidatedInput = options.forwardValidatedInput ?? false;
19
+ }
20
+ init(options) {
21
+ return {
22
+ ...options,
23
+ interceptors: [...toArray(options.interceptors), async ({ next, ...interceptorOptions }) => {
24
+ const procedure = getProcedureContractOrThrow(this.contract, interceptorOptions.path);
25
+ const inputSchemas = toArray(procedure["~orpc"].inputSchemas);
26
+ const originalInput = interceptorOptions.input;
27
+ let currentInput = originalInput;
28
+ for (const [index, schema] of inputSchemas.entries()) {
29
+ const validating = index !== 0 ? mergeTwoLevels(originalInput, currentInput) : currentInput;
30
+ const result = await schema["~standard"].validate(validating);
31
+ if (result.issues) throw new ORPCError("BAD_REQUEST", {
32
+ message: "Input validation failed",
33
+ data: { issues: result.issues },
34
+ cause: new ValidationError({
35
+ message: "Input validation failed",
36
+ issues: result.issues,
37
+ invalidData: validating
38
+ })
39
+ });
40
+ currentInput = index !== 0 ? mergeTwoLevels(currentInput, result.value) : result.value;
41
+ }
42
+ return this.forwardValidatedInput ? next({
43
+ ...interceptorOptions,
44
+ input: currentInput
45
+ }) : next();
46
+ }]
47
+ };
48
+ }
49
+ };
50
+ export { RequestValidationLinkPlugin };
@@ -0,0 +1,15 @@
1
+ import { RouterContract } from "../router.js";
2
+ import { ClientContext } from "@orpc/client";
3
+ import { StandardLinkOptions, StandardLinkPlugin } from "@orpc/client/standard";
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
+ }