@orpc/contract 2.0.0-beta.49 → 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 (43) hide show
  1. package/dist/builder-variants.d.ts +79 -79
  2. package/dist/builder.d.ts +52 -52
  3. package/dist/builder.js +106 -110
  4. package/dist/client-factory.d.ts +12 -12
  5. package/dist/client-factory.js +36 -36
  6. package/dist/error-factory.d.ts +20 -23
  7. package/dist/error-factory.js +105 -117
  8. package/dist/error-utils.d.ts +3 -3
  9. package/dist/error-utils.js +35 -38
  10. package/dist/error.d.ts +23 -27
  11. package/dist/error.js +21 -19
  12. package/dist/index.d.ts +20 -62
  13. package/dist/index.js +12 -31
  14. package/dist/meta-built-in.d.ts +10 -10
  15. package/dist/meta-built-in.js +41 -50
  16. package/dist/meta-utils.d.ts +10 -13
  17. package/dist/meta-utils.js +67 -73
  18. package/dist/meta.d.ts +27 -27
  19. package/dist/meta.js +9 -11
  20. package/dist/plugins/index.d.ts +3 -12
  21. package/dist/plugins/index.js +2 -12
  22. package/dist/plugins/request-validation.d.ts +19 -19
  23. package/dist/plugins/request-validation.js +49 -54
  24. package/dist/plugins/response-validation.d.ts +8 -8
  25. package/dist/plugins/response-validation.js +66 -71
  26. package/dist/procedure-client.d.ts +5 -5
  27. package/dist/procedure.d.ts +24 -24
  28. package/dist/procedure.js +17 -28
  29. package/dist/router-client.d.ts +5 -7
  30. package/dist/router-utils.d.ts +10 -17
  31. package/dist/router-utils.js +53 -73
  32. package/dist/router.d.ts +10 -20
  33. package/dist/schema-built-in.d.ts +5 -10
  34. package/dist/schema-built-in.js +64 -71
  35. package/dist/schema-utils.d.ts +3 -3
  36. package/dist/schema-utils.js +32 -40
  37. package/dist/schema.d.ts +2 -2
  38. package/package.json +3 -3
  39. package/dist/builder-variants.js +0 -1
  40. package/dist/procedure-client.js +0 -1
  41. package/dist/router-client.js +0 -1
  42. package/dist/router.js +0 -1
  43. package/dist/schema.js +0 -1
@@ -1,55 +1,50 @@
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';
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
5
6
  /**
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
- }
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 };
@@ -1,6 +1,6 @@
1
- import type { ClientContext } from '@orpc/client';
2
- import type { StandardLinkOptions, StandardLinkPlugin } from '@orpc/client/standard';
3
- import type { RouterContract } from '../router.ts';
1
+ import { RouterContract } from "../router.js";
2
+ import { ClientContext } from "@orpc/client";
3
+ import { StandardLinkOptions, StandardLinkPlugin } from "@orpc/client/standard";
4
4
  /**
5
5
  * Validates server responses against contract schemas before your application uses them.
6
6
  * This helps ensure the data returned by the server matches the types defined in your contract.
@@ -8,8 +8,8 @@ import type { RouterContract } from '../router.ts';
8
8
  * @see {@link https://orpc.dev/docs/plugins/response-validation | Response Validation Plugin}
9
9
  */
10
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
- }
11
+ private readonly contract;
12
+ name: string;
13
+ constructor(contract: RouterContract);
14
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
15
+ }
@@ -1,72 +1,67 @@
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';
1
+ import { ValidationError } from "../error.js";
2
+ import { reconcileORPCError } from "../error-utils.js";
3
+ import { getProcedureContractOrThrow } from "../router-utils.js";
4
+ import { isAsyncIteratorObject, override, toArray } from "@orpc/shared";
5
+ import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from "@orpc/client";
6
+ // src/plugins/response-validation.ts
6
7
  /**
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
- }
8
+ * Validates server responses against contract schemas before your application uses them.
9
+ * This helps ensure the data returned by the server matches the types defined in your contract.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/plugins/response-validation | Response Validation Plugin}
12
+ */
13
+ var ResponseValidationLinkPlugin = class {
14
+ contract;
15
+ name = "~response-validation";
16
+ constructor(contract) {
17
+ this.contract = contract;
18
+ }
19
+ init(options) {
20
+ return {
21
+ ...options,
22
+ interceptors: [
23
+ async ({ next, path }) => {
24
+ const procedure = getProcedureContractOrThrow(this.contract, path);
25
+ const reconcileError = async (error) => {
26
+ if (error instanceof ORPCError) return await reconcileORPCError(procedure["~orpc"].errorMap, error);
27
+ return error;
28
+ };
29
+ try {
30
+ const output = await next();
31
+ if (isAsyncIteratorObject(output))
32
+ /**
33
+ * Errors thrown while consuming the iterator must be reconciled too.
34
+ *
35
+ * @warning
36
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
37
+ */
38
+ return override(output, wrapAsyncIteratorPreservingEventMeta(output, { mapError: reconcileError }));
39
+ return output;
40
+ } catch (error) {
41
+ throw await reconcileError(error);
42
+ }
43
+ },
44
+ ...toArray(options.interceptors),
45
+ async ({ next, path }) => {
46
+ const procedure = getProcedureContractOrThrow(this.contract, path);
47
+ const outputSchemas = toArray(procedure["~orpc"].outputSchemas);
48
+ let output = await next();
49
+ for (let i = outputSchemas.length - 1; i >= 0; i--) {
50
+ const result = await outputSchemas[i]["~standard"].validate(output);
51
+ if (result.issues) throw new ORPCError("INTERNAL_SERVER_ERROR", {
52
+ message: "Output validation failed",
53
+ cause: new ValidationError({
54
+ message: "Output validation failed",
55
+ issues: result.issues,
56
+ invalidData: output
57
+ })
58
+ });
59
+ output = result.value;
60
+ }
61
+ return output;
62
+ }
63
+ ]
64
+ };
65
+ }
66
+ };
67
+ export { ResponseValidationLinkPlugin };
@@ -1,5 +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>;
1
+ import { ErrorMap, ORPCErrorFromErrorMap } from "./error.js";
2
+ import { AnySchema, InferSchemaInput, InferSchemaOutput } from "./schema.js";
3
+ import { ThrowableError } from "@orpc/shared";
4
+ import { Client, ClientContext } from "@orpc/client";
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>;
@@ -1,28 +1,28 @@
1
- import type { ErrorMap } from './error.ts';
2
- import type { AnyMetaPlugin, Meta } from './meta.ts';
3
- import type { AnySchema } from './schema.ts';
1
+ import { ErrorMap } from "./error.js";
2
+ import { AnyMetaPlugin, Meta } from "./meta.js";
3
+ import { AnySchema } from "./schema.js";
4
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;
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
19
  }
20
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;
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
27
  }
28
- export type AnyProcedureContract = ProcedureContract<any, any, any>;
28
+ export type AnyProcedureContract = ProcedureContract<any, any, any>;
package/dist/procedure.js CHANGED
@@ -1,28 +1,17 @@
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
- }
1
+ import { getConstructor, isNonPrimitive } from "@orpc/shared";
2
+ // src/procedure.ts
3
+ var ProcedureContract = class ProcedureContract {
4
+ "~orpc";
5
+ "constructor"(def) {
6
+ this["~orpc"] = def;
7
+ }
8
+ /**
9
+ * Checks if the given instance satisfies the {@link ProcedureContract} class/interface.
10
+ */
11
+ static [Symbol.hasInstance](instance) {
12
+ if (this !== ProcedureContract) return Function.prototype[Symbol.hasInstance].call(this, instance);
13
+ if (getConstructor(instance) === ProcedureContract) return true;
14
+ return isNonPrimitive(instance) && isNonPrimitive(instance["~orpc"]) && isNonPrimitive(instance["~orpc"].errorMap) && isNonPrimitive(instance["~orpc"].meta) && (instance["~orpc"].inputSchemas === void 0 || Array.isArray(instance["~orpc"].inputSchemas)) && (instance["~orpc"].outputSchemas === void 0 || Array.isArray(instance["~orpc"].outputSchemas));
15
+ }
16
+ };
17
+ export { ProcedureContract };
@@ -1,13 +1,11 @@
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';
1
+ import { ProcedureContract } from "./procedure.js";
2
+ import { ProcedureContractClient } from "./procedure-client.js";
3
+ import { RouterContract } from "./router.js";
4
+ import { ClientContext } from "@orpc/client";
5
5
  /**
6
6
  * Client type inferred from a router contract, preserving its shape.
7
7
  * Useful for typing a client without importing the server router.
8
8
  *
9
9
  * @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
10
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
- };
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> : { [K in keyof TRouter]: TRouter[K] extends RouterContract ? RouterContractClient<TRouter[K], TClientContext> : never; };
@@ -1,21 +1,14 @@
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
- };
1
+ import { ErrorMap } from "./error.js";
2
+ import { MergedErrorMap } from "./error-utils.js";
3
+ import { AnyMetaPlugin, Meta } from "./meta.js";
4
+ import { AnyProcedureContract, ProcedureContract } from "./procedure.js";
5
+ import { RouterContract } from "./router.js";
6
+ export type AugmentedContractRouter<T extends RouterContract, TErrorMap extends ErrorMap> = T extends ProcedureContract<infer $InputSchema, infer $OutputSchema, infer $Errors> ? ProcedureContract<$InputSchema, $OutputSchema, MergedErrorMap<TErrorMap, $Errors>> : { [K in keyof T]: T[K] extends RouterContract ? AugmentedContractRouter<T[K], TErrorMap> : never; };
10
7
  export interface AugmentContractRouterOptions<TErrorMap extends ErrorMap> {
11
- meta: Meta;
12
- metaPlugins?: AnyMetaPlugin[] | undefined;
13
- errorMap: TErrorMap;
8
+ meta: Meta;
9
+ metaPlugins?: AnyMetaPlugin[] | undefined;
10
+ errorMap: TErrorMap;
14
11
  }
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
12
  export declare function getRouterContract(router: RouterContract, path: readonly string[]): RouterContract | undefined;
20
13
  export declare function getProcedureContractOrThrow(router: RouterContract, path: readonly string[]): AnyProcedureContract;
21
14
  /**
@@ -27,4 +20,4 @@ export declare function getProcedureContractOrThrow(router: RouterContract, path
27
20
  *
28
21
  * @see {@link https://orpc.dev/docs/contract/router | Router Contract}
29
22
  */
30
- export declare function minifyRouterContract(router: RouterContract): RouterContract;
23
+ export declare function minifyRouterContract(router: RouterContract): RouterContract;
@@ -1,79 +1,59 @@
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';
1
+ import { mergeErrorMap } from "./error-utils.js";
2
+ import { resolveMetaPlugins } from "./meta-utils.js";
3
+ import { ProcedureContract } from "./procedure.js";
4
+ import { getOwn, isNonPrimitive, setOwn } from "@orpc/shared";
5
+ // src/router-utils.ts
5
6
  /**
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;
7
+ * Add capabilities without changing identity of the router contract
8
+ */
9
+ function augmentContractRouter(router, options) {
10
+ if (router instanceof ProcedureContract) {
11
+ const [meta, metaPlugins] = resolveMetaPlugins(options.meta, options.metaPlugins, router["~orpc"].metaPlugins);
12
+ return new ProcedureContract({
13
+ ...router["~orpc"],
14
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
15
+ meta,
16
+ metaPlugins
17
+ });
18
+ }
19
+ if (!isNonPrimitive(router)) return router;
20
+ const enhanced = {};
21
+ for (const key of Object.keys(router)) setOwn(enhanced, key, augmentContractRouter(router[key], options));
22
+ return enhanced;
27
23
  }
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;
24
+ function getRouterContract(router, path) {
25
+ let current = router;
26
+ for (let i = 0; i < path.length; i++) {
27
+ const segment = path[i];
28
+ if (!isNonPrimitive(current)) return;
29
+ if (current instanceof ProcedureContract) return;
30
+ current = getOwn(current, segment);
31
+ }
32
+ if (!isNonPrimitive(current)) return;
33
+ return current;
44
34
  }
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;
35
+ function getProcedureContractOrThrow(router, path) {
36
+ const procedure = getRouterContract(router, path);
37
+ if (!(procedure instanceof ProcedureContract)) throw new TypeError(`No valid procedure found at path "${path.join(".")}", this may happen when the router contract is not properly configured.`);
38
+ return procedure;
51
39
  }
52
40
  /**
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;
41
+ * Minifies a router contract so it can be safely exported to the client
42
+ * without exposing internal logic.
43
+ *
44
+ * @remarks
45
+ * **Note**: Only the metadata needed by the client is preserved; all other data is stripped out.
46
+ *
47
+ * @see {@link https://orpc.dev/docs/contract/router | Router Contract}
48
+ */
49
+ function minifyRouterContract(router) {
50
+ if (router instanceof ProcedureContract) return { "~orpc": {
51
+ errorMap: {},
52
+ meta: router["~orpc"].meta
53
+ } };
54
+ if (!isNonPrimitive(router)) return router;
55
+ const json = {};
56
+ for (const [key, child] of Object.entries(router)) setOwn(json, key, minifyRouterContract(child));
57
+ return json;
79
58
  }
59
+ export { augmentContractRouter, getProcedureContractOrThrow, getRouterContract, minifyRouterContract };