@orpc/contract 2.0.0-beta.47 → 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.
- package/README.md +6 -7
- package/dist/builder-variants.d.ts +103 -0
- package/dist/builder-variants.js +1 -0
- package/dist/builder.d.ts +78 -0
- package/dist/builder.js +112 -0
- package/dist/client-factory.d.ts +24 -0
- package/dist/client-factory.js +38 -0
- package/dist/error-factory.d.ts +80 -0
- package/dist/error-factory.js +121 -0
- package/dist/error-utils.d.ts +5 -0
- package/dist/error-utils.js +40 -0
- package/dist/error.d.ts +45 -0
- package/dist/error.js +20 -0
- package/dist/index.d.ts +44 -415
- package/dist/index.js +31 -0
- package/dist/meta-built-in.d.ts +30 -0
- package/dist/meta-built-in.js +54 -0
- package/dist/meta-utils.d.ts +58 -0
- package/dist/meta-utils.js +76 -0
- package/dist/meta.d.ts +53 -0
- package/dist/meta.js +13 -0
- package/dist/plugins/index.d.ts +8 -43
- package/dist/plugins/index.js +12 -0
- package/dist/plugins/request-validation.d.ts +28 -0
- package/dist/plugins/request-validation.js +55 -0
- package/dist/plugins/response-validation.d.ts +15 -0
- package/dist/plugins/response-validation.js +72 -0
- package/dist/procedure-client.d.ts +5 -0
- package/dist/procedure-client.js +1 -0
- package/dist/procedure.d.ts +28 -0
- package/dist/procedure.js +28 -0
- package/dist/router-client.d.ts +13 -0
- package/dist/router-client.js +1 -0
- package/dist/router-utils.d.ts +30 -0
- package/dist/router-utils.js +79 -0
- package/dist/router.d.ts +52 -0
- package/dist/router.js +1 -0
- package/dist/schema-built-in.d.ts +23 -0
- package/dist/schema-built-in.js +76 -0
- package/dist/schema-utils.d.ts +20 -0
- package/dist/schema-utils.js +44 -0
- package/dist/schema.d.ts +25 -0
- package/dist/schema.js +1 -0
- package/package.json +29 -31
- package/dist/index.d.mts +0 -433
- package/dist/index.mjs +0 -342
- package/dist/plugins/index.d.mts +0 -47
- package/dist/plugins/index.mjs +0 -91
- package/dist/shared/contract.CM62dTQK.d.mts +0 -202
- package/dist/shared/contract.CM62dTQK.d.ts +0 -202
- package/dist/shared/contract.T7BNVKJ4.mjs +0 -177
|
@@ -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
|
+
}
|
package/dist/plugins/index.d.ts
CHANGED
|
@@ -1,47 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import { RouterContract } from '../index.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
|
-
}
|
|
1
|
+
export * from './request-validation.ts';
|
|
2
|
+
export {
|
|
19
3
|
/**
|
|
20
|
-
*
|
|
21
|
-
* This is useful when your application relies on server-side validation.
|
|
22
|
-
*
|
|
23
|
-
* @see {@link https://orpc.dev/docs/plugins/request-validation | Request Validation Plugin}
|
|
4
|
+
* @deprecated Use `RequestValidationLinkPlugin` instead.
|
|
24
5
|
*/
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
private readonly forwardValidatedInput;
|
|
29
|
-
constructor(contract: RouterContract, options?: RequestValidationLinkPluginOptions<T>);
|
|
30
|
-
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
31
|
-
}
|
|
32
|
-
|
|
6
|
+
RequestValidationLinkPlugin as RequestValidationPlugin, } from './request-validation.ts';
|
|
7
|
+
export * from './response-validation.ts';
|
|
8
|
+
export {
|
|
33
9
|
/**
|
|
34
|
-
*
|
|
35
|
-
* This helps ensure the data returned by the server matches the types defined in your contract.
|
|
36
|
-
*
|
|
37
|
-
* @see {@link https://orpc.dev/docs/plugins/response-validation | Response Validation Plugin}
|
|
10
|
+
* @deprecated Use `ResponseValidationLinkPlugin` instead.
|
|
38
11
|
*/
|
|
39
|
-
|
|
40
|
-
private readonly contract;
|
|
41
|
-
name: string;
|
|
42
|
-
constructor(contract: RouterContract);
|
|
43
|
-
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export { RequestValidationLinkPlugin, RequestValidationLinkPlugin as RequestValidationPlugin, ResponseValidationLinkPlugin, ResponseValidationLinkPlugin as ResponseValidationPlugin };
|
|
47
|
-
export type { RequestValidationLinkPluginOptions };
|
|
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>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ErrorMap } from './error.ts';
|
|
2
|
+
import type { AnyMetaPlugin, Meta } from './meta.ts';
|
|
3
|
+
import type { AnySchema } from './schema.ts';
|
|
4
|
+
export interface ProcedureContractDefinition<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> {
|
|
5
|
+
__TInputSchema?: {
|
|
6
|
+
type: TInputSchema;
|
|
7
|
+
};
|
|
8
|
+
__TOutputSchema?: {
|
|
9
|
+
type: TOutputSchema;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Non-serializable should be optional
|
|
13
|
+
*/
|
|
14
|
+
inputSchemas?: AnySchema[] | undefined;
|
|
15
|
+
outputSchemas?: AnySchema[] | undefined;
|
|
16
|
+
metaPlugins?: AnyMetaPlugin[] | undefined;
|
|
17
|
+
errorMap: TErrorMap;
|
|
18
|
+
meta: Meta;
|
|
19
|
+
}
|
|
20
|
+
export declare class ProcedureContract<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> {
|
|
21
|
+
'~orpc': ProcedureContractDefinition<TInputSchema, TOutputSchema, TErrorMap>;
|
|
22
|
+
constructor(def: ProcedureContractDefinition<TInputSchema, TOutputSchema, TErrorMap>);
|
|
23
|
+
/**
|
|
24
|
+
* Checks if the given instance satisfies the {@link ProcedureContract} class/interface.
|
|
25
|
+
*/
|
|
26
|
+
static [Symbol.hasInstance](instance: unknown): boolean;
|
|
27
|
+
}
|
|
28
|
+
export type AnyProcedureContract = ProcedureContract<any, any, any>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { getConstructor, isNonPrimitive } from '@orpc/shared';
|
|
2
|
+
export class ProcedureContract {
|
|
3
|
+
'~orpc';
|
|
4
|
+
constructor(def) {
|
|
5
|
+
this['~orpc'] = def;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Checks if the given instance satisfies the {@link ProcedureContract} class/interface.
|
|
9
|
+
*/
|
|
10
|
+
static [Symbol.hasInstance](instance) {
|
|
11
|
+
if (this !== ProcedureContract) {
|
|
12
|
+
// fallback to default instanceof check if this is extended class
|
|
13
|
+
return Function.prototype[Symbol.hasInstance].call(this, instance);
|
|
14
|
+
}
|
|
15
|
+
const constructor = getConstructor(instance);
|
|
16
|
+
if (constructor === ProcedureContract) {
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
return (isNonPrimitive(instance) &&
|
|
20
|
+
isNonPrimitive(instance['~orpc']) &&
|
|
21
|
+
isNonPrimitive(instance['~orpc'].errorMap) &&
|
|
22
|
+
isNonPrimitive(instance['~orpc'].meta) &&
|
|
23
|
+
(instance['~orpc'].inputSchemas === undefined ||
|
|
24
|
+
Array.isArray(instance['~orpc'].inputSchemas)) &&
|
|
25
|
+
(instance['~orpc'].outputSchemas === undefined ||
|
|
26
|
+
Array.isArray(instance['~orpc'].outputSchemas)));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ClientContext } from '@orpc/client';
|
|
2
|
+
import type { ProcedureContractClient } from './procedure-client.ts';
|
|
3
|
+
import type { ProcedureContract } from './procedure.ts';
|
|
4
|
+
import type { RouterContract } from './router.ts';
|
|
5
|
+
/**
|
|
6
|
+
* Client type inferred from a router contract, preserving its shape.
|
|
7
|
+
* Useful for typing a client without importing the server router.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
|
|
10
|
+
*/
|
|
11
|
+
export type RouterContractClient<TRouter extends RouterContract, TClientContext extends ClientContext = object> = TRouter extends ProcedureContract<infer UInputSchema, infer UOutputSchema, infer UErrorMap> ? ProcedureContractClient<TClientContext, UInputSchema, UOutputSchema, UErrorMap> : {
|
|
12
|
+
[K in keyof TRouter]: TRouter[K] extends RouterContract ? RouterContractClient<TRouter[K], TClientContext> : never;
|
|
13
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { MergedErrorMap } from './error-utils.ts';
|
|
2
|
+
import type { ErrorMap } from './error.ts';
|
|
3
|
+
import type { AnyMetaPlugin, Meta } from './meta.ts';
|
|
4
|
+
import type { AnyProcedureContract } from './procedure.ts';
|
|
5
|
+
import { ProcedureContract } from './procedure.ts';
|
|
6
|
+
import type { RouterContract } from './router.ts';
|
|
7
|
+
export type AugmentedContractRouter<T extends RouterContract, TErrorMap extends ErrorMap> = T extends ProcedureContract<infer $InputSchema, infer $OutputSchema, infer $Errors> ? ProcedureContract<$InputSchema, $OutputSchema, MergedErrorMap<TErrorMap, $Errors>> : {
|
|
8
|
+
[K in keyof T]: T[K] extends RouterContract ? AugmentedContractRouter<T[K], TErrorMap> : never;
|
|
9
|
+
};
|
|
10
|
+
export interface AugmentContractRouterOptions<TErrorMap extends ErrorMap> {
|
|
11
|
+
meta: Meta;
|
|
12
|
+
metaPlugins?: AnyMetaPlugin[] | undefined;
|
|
13
|
+
errorMap: TErrorMap;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Add capabilities without changing identity of the router contract
|
|
17
|
+
*/
|
|
18
|
+
export declare function augmentContractRouter<T extends RouterContract, TErrorMap extends ErrorMap>(router: T, options: AugmentContractRouterOptions<TErrorMap>): AugmentedContractRouter<T, TErrorMap>;
|
|
19
|
+
export declare function getRouterContract(router: RouterContract, path: readonly string[]): RouterContract | undefined;
|
|
20
|
+
export declare function getProcedureContractOrThrow(router: RouterContract, path: readonly string[]): AnyProcedureContract;
|
|
21
|
+
/**
|
|
22
|
+
* Minifies a router contract so it can be safely exported to the client
|
|
23
|
+
* without exposing internal logic.
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* **Note**: Only the metadata needed by the client is preserved; all other data is stripped out.
|
|
27
|
+
*
|
|
28
|
+
* @see {@link https://orpc.dev/docs/contract/router | Router Contract}
|
|
29
|
+
*/
|
|
30
|
+
export declare function minifyRouterContract(router: RouterContract): RouterContract;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { getOwn, isNonPrimitive, setOwn } from '@orpc/shared';
|
|
2
|
+
import { mergeErrorMap } from './error-utils.js';
|
|
3
|
+
import { resolveMetaPlugins } from './meta-utils.js';
|
|
4
|
+
import { ProcedureContract } from './procedure.js';
|
|
5
|
+
/**
|
|
6
|
+
* Add capabilities without changing identity of the router contract
|
|
7
|
+
*/
|
|
8
|
+
export function augmentContractRouter(router, options) {
|
|
9
|
+
if (router instanceof ProcedureContract) {
|
|
10
|
+
const [meta, metaPlugins] = resolveMetaPlugins(options.meta, options.metaPlugins, router['~orpc'].metaPlugins);
|
|
11
|
+
const enhanced = new ProcedureContract({
|
|
12
|
+
...router['~orpc'],
|
|
13
|
+
errorMap: mergeErrorMap(options.errorMap, router['~orpc'].errorMap),
|
|
14
|
+
meta,
|
|
15
|
+
metaPlugins,
|
|
16
|
+
});
|
|
17
|
+
return enhanced;
|
|
18
|
+
}
|
|
19
|
+
if (!isNonPrimitive(router)) {
|
|
20
|
+
return router;
|
|
21
|
+
}
|
|
22
|
+
const enhanced = {};
|
|
23
|
+
for (const key of Object.keys(router)) {
|
|
24
|
+
setOwn(enhanced, key, augmentContractRouter(router[key], options));
|
|
25
|
+
}
|
|
26
|
+
return enhanced;
|
|
27
|
+
}
|
|
28
|
+
export function getRouterContract(router, path) {
|
|
29
|
+
let current = router;
|
|
30
|
+
for (let i = 0; i < path.length; i++) {
|
|
31
|
+
const segment = path[i];
|
|
32
|
+
if (!isNonPrimitive(current)) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
if (current instanceof ProcedureContract) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
current = getOwn(current, segment);
|
|
39
|
+
}
|
|
40
|
+
if (!isNonPrimitive(current)) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
return current;
|
|
44
|
+
}
|
|
45
|
+
export function getProcedureContractOrThrow(router, path) {
|
|
46
|
+
const procedure = getRouterContract(router, path);
|
|
47
|
+
if (!(procedure instanceof ProcedureContract)) {
|
|
48
|
+
throw new TypeError(`No valid procedure found at path "${path.join('.')}", this may happen when the router contract is not properly configured.`);
|
|
49
|
+
}
|
|
50
|
+
return procedure;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Minifies a router contract so it can be safely exported to the client
|
|
54
|
+
* without exposing internal logic.
|
|
55
|
+
*
|
|
56
|
+
* @remarks
|
|
57
|
+
* **Note**: Only the metadata needed by the client is preserved; all other data is stripped out.
|
|
58
|
+
*
|
|
59
|
+
* @see {@link https://orpc.dev/docs/contract/router | Router Contract}
|
|
60
|
+
*/
|
|
61
|
+
export function minifyRouterContract(router) {
|
|
62
|
+
if (router instanceof ProcedureContract) {
|
|
63
|
+
const procedure = {
|
|
64
|
+
'~orpc': {
|
|
65
|
+
errorMap: {},
|
|
66
|
+
meta: router['~orpc'].meta,
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
return procedure;
|
|
70
|
+
}
|
|
71
|
+
if (!isNonPrimitive(router)) {
|
|
72
|
+
return router;
|
|
73
|
+
}
|
|
74
|
+
const json = {};
|
|
75
|
+
for (const [key, child] of Object.entries(router)) {
|
|
76
|
+
setOwn(json, key, minifyRouterContract(child));
|
|
77
|
+
}
|
|
78
|
+
return json;
|
|
79
|
+
}
|