@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.mts DELETED
@@ -1,182 +0,0 @@
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.mjs';
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.mjs';
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 };
package/dist/index.mjs DELETED
@@ -1,193 +0,0 @@
1
- import { isTypescriptObject, toArray, set, get, ORPC_NAME, isAsyncIteratorObject, isPropertyKey } from '@orpc/shared';
2
- import { P as ProcedureContract, r as resolveMetaPlugins, m as mergeErrorMap, a as augmentContractRouter, V as ValidationError } from './shared/contract.CW-2wl1i.mjs';
3
- export { d as defineMeta, g as getProcedureContractOrThrow, b as getRouterContract, c as minifyRouterContract, e as reconcileORPCError } from './shared/contract.CW-2wl1i.mjs';
4
- import { createORPCClient, wrapEventIteratorPreservingMeta, ORPCError } from '@orpc/client';
5
-
6
- const HIDDEN_META_PLUGINS_SYMBOL = Symbol.for("ORPC_HIDDEN_META_PLUGINS");
7
- function getHiddenMetaPlugins(container) {
8
- if (!isTypescriptObject(container)) {
9
- return void 0;
10
- }
11
- return container[HIDDEN_META_PLUGINS_SYMBOL];
12
- }
13
- function setHiddenMetaPlugins(container, metaPlugins) {
14
- container[HIDDEN_META_PLUGINS_SYMBOL] = metaPlugins;
15
- }
16
-
17
- class ContractBuilder extends ProcedureContract {
18
- /**
19
- * Private constructor to prevent direct instantiation.
20
- * Use the static `create` method to initialize a new instance with a safe initial definition.
21
- */
22
- constructor(definition) {
23
- super(definition);
24
- }
25
- static create() {
26
- return new ContractBuilder({
27
- errorMap: {},
28
- meta: {}
29
- });
30
- }
31
- meta(...plugins) {
32
- const [meta, metaPlugins] = resolveMetaPlugins(
33
- this["~orpc"].meta,
34
- this["~orpc"].metaPlugins,
35
- plugins
36
- );
37
- return new ContractBuilder({
38
- ...this["~orpc"],
39
- meta,
40
- metaPlugins
41
- });
42
- }
43
- errors(errors) {
44
- let result = new ContractBuilder({
45
- ...this["~orpc"],
46
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
47
- });
48
- const plugins = getHiddenMetaPlugins(errors);
49
- if (plugins) {
50
- result = result.meta(...plugins);
51
- }
52
- return result;
53
- }
54
- input(schema) {
55
- let result = new ContractBuilder({
56
- ...this["~orpc"],
57
- inputSchemas: [...toArray(this["~orpc"].inputSchemas), schema]
58
- });
59
- const plugins = getHiddenMetaPlugins(schema);
60
- if (plugins) {
61
- result = result.meta(...plugins);
62
- }
63
- return result;
64
- }
65
- output(schema) {
66
- let result = new ContractBuilder({
67
- ...this["~orpc"],
68
- outputSchemas: [...toArray(this["~orpc"].outputSchemas), schema]
69
- });
70
- const plugins = getHiddenMetaPlugins(schema);
71
- if (plugins) {
72
- result = result.meta(...plugins);
73
- }
74
- return result;
75
- }
76
- router(router) {
77
- return augmentContractRouter(router, this["~orpc"]);
78
- }
79
- }
80
- const oc = ContractBuilder.create();
81
-
82
- const meta = {
83
- path(path) {
84
- return {
85
- name: "~path",
86
- init(meta2) {
87
- return {
88
- ...meta2,
89
- "~path": path
90
- };
91
- }
92
- };
93
- }
94
- };
95
- function getPathMeta(procedureOrLazy) {
96
- return procedureOrLazy["~orpc"].meta["~path"];
97
- }
98
-
99
- function createContractCaller(link, options = {}) {
100
- return async (procedure, ...rest) => {
101
- const path = getPathMeta(procedure);
102
- if (!path) {
103
- throw new TypeError(
104
- "ContractCaller: procedure contract must define `meta.path` that matches its path in the root router contract."
105
- );
106
- }
107
- if (options.contractRef) {
108
- set(options.contractRef, [...path, "~orpc"], procedure["~orpc"]);
109
- }
110
- const scoped = get(options.scoped, path);
111
- if (scoped !== void 0 && (scoped === null || typeof scoped !== "object")) {
112
- throw new TypeError(
113
- `ContractCaller: "scoped" at path "${path.join(".")}" must be an object or undefined, got "${scoped}".`
114
- );
115
- }
116
- const client = createORPCClient(link, { path, interceptors: options.interceptors, scoped });
117
- return client(...rest);
118
- };
119
- }
120
-
121
- const EVENT_ITERATOR_SCHEMA_DETAILS_SYMBOL = Symbol.for("ORPC_EVENT_ITERATOR_SCHEMA_DETAILS");
122
- function eventIterator(yieldSchema, returnSchema) {
123
- return {
124
- "~standard": {
125
- [EVENT_ITERATOR_SCHEMA_DETAILS_SYMBOL]: { yieldSchema, returnSchema },
126
- vendor: ORPC_NAME,
127
- version: 1,
128
- validate(iterator) {
129
- if (!isAsyncIteratorObject(iterator)) {
130
- return { issues: [{ message: "Expect event iterator", path: [] }] };
131
- }
132
- const mapped = wrapEventIteratorPreservingMeta(iterator, {
133
- async mapResult(result) {
134
- const schema = result.done ? returnSchema : yieldSchema;
135
- if (!schema) {
136
- return result;
137
- }
138
- const validated = await schema["~standard"].validate(result.value);
139
- if (validated.issues) {
140
- throw new ORPCError("EVENT_ITERATOR_VALIDATION_FAILED", {
141
- message: "Event iterator validation failed",
142
- cause: new ValidationError({
143
- issues: validated.issues,
144
- message: "Event iterator validation failed",
145
- invalidData: result.value
146
- })
147
- });
148
- }
149
- return { done: result.done, value: validated.value };
150
- }
151
- });
152
- return { value: mapped };
153
- }
154
- }
155
- };
156
- }
157
- function getEventIteratorSchemaDetails(schema) {
158
- if (schema === void 0) {
159
- return void 0;
160
- }
161
- return schema["~standard"][EVENT_ITERATOR_SCHEMA_DETAILS_SYMBOL];
162
- }
163
-
164
- function type(...[map]) {
165
- return {
166
- "~standard": {
167
- vendor: ORPC_NAME,
168
- version: 1,
169
- async validate(value) {
170
- if (map) {
171
- return { value: await map(value) };
172
- }
173
- return { value };
174
- }
175
- }
176
- };
177
- }
178
- function isSchemaIssue(issue) {
179
- if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
180
- return false;
181
- }
182
- if (issue.path !== void 0) {
183
- if (!Array.isArray(issue.path)) {
184
- return false;
185
- }
186
- if (!issue.path.every((segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key))) {
187
- return false;
188
- }
189
- }
190
- return true;
191
- }
192
-
193
- export { ContractBuilder, HIDDEN_META_PLUGINS_SYMBOL, ProcedureContract, ValidationError, augmentContractRouter, createContractCaller, eventIterator, getEventIteratorSchemaDetails, getHiddenMetaPlugins, getPathMeta, isSchemaIssue, mergeErrorMap, meta, oc, resolveMetaPlugins, setHiddenMetaPlugins, type };
@@ -1,38 +0,0 @@
1
- import { ClientContext } from '@orpc/client';
2
- import { StandardLinkPlugin, StandardLinkOptions } from '@orpc/client/standard';
3
- import { R as RouterContract } from '../shared/contract.Do92aRJ4.mjs';
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,90 +0,0 @@
1
- import { ORPCError } from '@orpc/client';
2
- import { toArray } from '@orpc/shared';
3
- import { g as getProcedureContractOrThrow, V as ValidationError, e as reconcileORPCError } from '../shared/contract.CW-2wl1i.mjs';
4
-
5
- class RequestValidationLinkPlugin {
6
- constructor(contract, options = {}) {
7
- this.contract = contract;
8
- this.forwardValidatedInput = options.forwardValidatedInput ?? false;
9
- }
10
- name = "~request-validation";
11
- forwardValidatedInput;
12
- init(options) {
13
- return {
14
- ...options,
15
- interceptors: [...toArray(options.interceptors), async ({ next, ...interceptorOptions }) => {
16
- const procedure = getProcedureContractOrThrow(this.contract, interceptorOptions.path);
17
- let currentInput = interceptorOptions.input;
18
- if (procedure["~orpc"].inputSchemas) {
19
- for (const schema of procedure["~orpc"].inputSchemas) {
20
- const result = await schema["~standard"].validate(currentInput);
21
- if (result.issues) {
22
- throw new ORPCError("BAD_REQUEST", {
23
- message: "Input validation failed",
24
- data: {
25
- issues: result.issues
26
- },
27
- cause: new ValidationError({
28
- message: "Input validation failed",
29
- issues: result.issues,
30
- invalidData: currentInput
31
- })
32
- });
33
- }
34
- currentInput = result.value;
35
- }
36
- }
37
- return this.forwardValidatedInput ? next({ ...interceptorOptions, input: currentInput }) : next();
38
- }]
39
- };
40
- }
41
- }
42
-
43
- class ResponseValidationLinkPlugin {
44
- constructor(contract) {
45
- this.contract = contract;
46
- }
47
- name = "~response-validation";
48
- init(options) {
49
- return {
50
- ...options,
51
- interceptors: [
52
- async ({ next, path }) => {
53
- const procedure = getProcedureContractOrThrow(this.contract, path);
54
- try {
55
- return await next();
56
- } catch (error) {
57
- if (error instanceof ORPCError) {
58
- throw await reconcileORPCError(procedure["~orpc"].errorMap, error);
59
- }
60
- throw error;
61
- }
62
- },
63
- ...toArray(options.interceptors),
64
- async ({ next, path }) => {
65
- const procedure = getProcedureContractOrThrow(this.contract, path);
66
- const outputSchemas = toArray(procedure["~orpc"].outputSchemas);
67
- let output = await next();
68
- for (let i = outputSchemas.length - 1; i >= 0; i--) {
69
- const schema = outputSchemas[i];
70
- const result = await schema["~standard"].validate(output);
71
- if (result.issues) {
72
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
73
- message: "Output validation failed",
74
- cause: new ValidationError({
75
- message: "Output validation failed",
76
- issues: result.issues,
77
- invalidData: output
78
- })
79
- });
80
- }
81
- output = result.value;
82
- }
83
- return output;
84
- }
85
- ]
86
- };
87
- }
88
- }
89
-
90
- export { RequestValidationLinkPlugin, ResponseValidationLinkPlugin };
@@ -1,180 +0,0 @@
1
- import { toArray, getConstructor, isTypescriptObject } from '@orpc/shared';
2
- import { cloneORPCError } from '@orpc/client';
3
-
4
- function mergeErrorMap(errorMap1, errorMap2) {
5
- return { ...errorMap1, ...errorMap2 };
6
- }
7
- async function reconcileORPCError(map, error) {
8
- const config = map[error.code];
9
- if (!config) {
10
- if (!error.defined) {
11
- return error;
12
- }
13
- const cloned2 = cloneORPCError(error);
14
- cloned2.defined = false;
15
- cloned2.inferable = false;
16
- return cloned2;
17
- }
18
- if (!config.data) {
19
- if (error.defined && error.inferable) {
20
- return error;
21
- }
22
- const cloned2 = cloneORPCError(error);
23
- cloned2.defined = true;
24
- cloned2.inferable = true;
25
- return cloned2;
26
- }
27
- const validated = await config.data["~standard"].validate(error.data);
28
- if (validated.issues) {
29
- if (!error.defined) {
30
- return error;
31
- }
32
- const cloned2 = cloneORPCError(error);
33
- cloned2.defined = false;
34
- cloned2.inferable = false;
35
- return cloned2;
36
- }
37
- if (error.data === validated.value && error.defined && error.inferable) {
38
- return error;
39
- }
40
- const cloned = cloneORPCError(error);
41
- cloned.data = validated.value;
42
- cloned.defined = true;
43
- cloned.inferable = true;
44
- return cloned;
45
- }
46
-
47
- function resolveMetaPlugins(baseMeta, existingPlugins, incomingPlugins) {
48
- existingPlugins = toArray(existingPlugins);
49
- incomingPlugins = toArray(incomingPlugins);
50
- let meta = baseMeta;
51
- for (const plugin of incomingPlugins) {
52
- if (plugin.init) {
53
- meta = plugin.init(meta);
54
- }
55
- }
56
- const plugins = [...existingPlugins, ...incomingPlugins];
57
- for (const plugin of plugins) {
58
- if (plugin.apply) {
59
- meta = plugin.apply(meta);
60
- }
61
- }
62
- return [meta, plugins];
63
- }
64
- function defineMeta(name, merge) {
65
- const metaPlugin = (value) => ({
66
- name,
67
- init: (meta) => {
68
- const current = meta[name];
69
- return {
70
- ...meta,
71
- [name]: merge(value, current)
72
- };
73
- }
74
- });
75
- const getMeta = (procedureOrLazy) => procedureOrLazy["~orpc"].meta[name];
76
- return [metaPlugin, getMeta];
77
- }
78
-
79
- class ProcedureContract {
80
- "~orpc";
81
- constructor(def) {
82
- this["~orpc"] = def;
83
- }
84
- /**
85
- * Checks if the given instance satisfies the {@see ProcedureContract} class/interface.
86
- */
87
- static [Symbol.hasInstance](instance) {
88
- if (this !== ProcedureContract) {
89
- return Function.prototype[Symbol.hasInstance].call(this, instance);
90
- }
91
- const constructor = getConstructor(instance);
92
- if (constructor === ProcedureContract) {
93
- return true;
94
- }
95
- return isTypescriptObject(instance) && isTypescriptObject(instance["~orpc"]) && isTypescriptObject(instance["~orpc"].errorMap) && isTypescriptObject(instance["~orpc"].meta) && (instance["~orpc"].inputSchemas === void 0 || Array.isArray(instance["~orpc"].inputSchemas)) && (instance["~orpc"].outputSchemas === void 0 || Array.isArray(instance["~orpc"].outputSchemas));
96
- }
97
- }
98
-
99
- function augmentContractRouter(router, options) {
100
- if (router instanceof ProcedureContract) {
101
- const [meta, metaPlugins] = resolveMetaPlugins(
102
- options.meta,
103
- options.metaPlugins,
104
- router["~orpc"].metaPlugins
105
- );
106
- const enhanced2 = new ProcedureContract({
107
- ...router["~orpc"],
108
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
109
- meta,
110
- metaPlugins
111
- });
112
- return enhanced2;
113
- }
114
- if (!isTypescriptObject(router)) {
115
- return router;
116
- }
117
- const enhanced = {};
118
- for (const key in router) {
119
- enhanced[key] = augmentContractRouter(router[key], options);
120
- }
121
- return enhanced;
122
- }
123
- function getRouterContract(router, path) {
124
- let current = router;
125
- for (let i = 0; i < path.length; i++) {
126
- const segment = path[i];
127
- if (!isTypescriptObject(current)) {
128
- return void 0;
129
- }
130
- if (current instanceof ProcedureContract) {
131
- return void 0;
132
- }
133
- current = current[segment];
134
- }
135
- if (!isTypescriptObject(current)) {
136
- return void 0;
137
- }
138
- return current;
139
- }
140
- function getProcedureContractOrThrow(router, path) {
141
- const procedure = getRouterContract(router, path);
142
- if (!(procedure instanceof ProcedureContract)) {
143
- throw new TypeError(`No valid procedure found at path "${path.join(".")}", this may happen when the router contract is not properly configured.`);
144
- }
145
- return procedure;
146
- }
147
- function minifyRouterContract(router) {
148
- if (router instanceof ProcedureContract) {
149
- const procedure = {
150
- "~orpc": {
151
- errorMap: {},
152
- meta: router["~orpc"].meta
153
- }
154
- };
155
- return procedure;
156
- }
157
- if (!isTypescriptObject(router)) {
158
- return router;
159
- }
160
- const json = {};
161
- for (const key in router) {
162
- json[key] = minifyRouterContract(router[key]);
163
- }
164
- return json;
165
- }
166
-
167
- class ValidationError extends Error {
168
- /**
169
- * This array is readonly because the upstream Standard Schema returns readonly issues.
170
- */
171
- issues;
172
- invalidData;
173
- constructor(options) {
174
- super(options.message, options);
175
- this.issues = options.issues;
176
- this.invalidData = options.invalidData;
177
- }
178
- }
179
-
180
- export { ProcedureContract as P, ValidationError as V, augmentContractRouter as a, getRouterContract as b, minifyRouterContract as c, defineMeta as d, reconcileORPCError as e, getProcedureContractOrThrow as g, mergeErrorMap as m, resolveMetaPlugins as r };