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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +4 -4
  2. package/dist/builder-variants.d.ts +103 -0
  3. package/dist/builder.d.ts +78 -0
  4. package/dist/builder.js +112 -0
  5. package/dist/client-factory.d.ts +24 -0
  6. package/dist/client-factory.js +38 -0
  7. package/dist/error-factory.d.ts +80 -0
  8. package/dist/error-factory.js +121 -0
  9. package/dist/error-utils.d.ts +5 -0
  10. package/dist/error-utils.js +40 -0
  11. package/dist/error.d.ts +45 -0
  12. package/dist/error.js +20 -0
  13. package/dist/index.d.ts +62 -0
  14. package/dist/index.js +31 -0
  15. package/dist/meta-built-in.d.ts +30 -0
  16. package/dist/meta-built-in.js +54 -0
  17. package/dist/meta-utils.d.ts +58 -0
  18. package/dist/meta-utils.js +76 -0
  19. package/dist/meta.d.ts +53 -0
  20. package/dist/meta.js +13 -0
  21. package/dist/plugins/index.d.ts +12 -0
  22. package/dist/plugins/index.js +12 -0
  23. package/dist/plugins/request-validation.d.ts +28 -0
  24. package/dist/plugins/request-validation.js +55 -0
  25. package/dist/plugins/response-validation.d.ts +15 -0
  26. package/dist/plugins/response-validation.js +72 -0
  27. package/dist/procedure-client.d.ts +5 -0
  28. package/dist/procedure.d.ts +28 -0
  29. package/dist/procedure.js +28 -0
  30. package/dist/router-client.d.ts +13 -0
  31. package/dist/router-utils.d.ts +30 -0
  32. package/dist/router-utils.js +79 -0
  33. package/dist/router.d.ts +52 -0
  34. package/dist/schema-built-in.d.ts +23 -0
  35. package/dist/schema-built-in.js +76 -0
  36. package/dist/schema-utils.d.ts +20 -0
  37. package/dist/schema-utils.js +44 -0
  38. package/dist/schema.d.ts +25 -0
  39. package/package.json +28 -30
  40. package/dist/builder-variants.d.mts +0 -113
  41. package/dist/builder.d.mts +0 -78
  42. package/dist/builder.mjs +0 -71
  43. package/dist/client-factory.d.mts +0 -24
  44. package/dist/client-factory.mjs +0 -34
  45. package/dist/error-factory.d.mts +0 -87
  46. package/dist/error-factory.mjs +0 -75
  47. package/dist/error-utils.d.mts +0 -11
  48. package/dist/error-utils.mjs +0 -43
  49. package/dist/error.d.mts +0 -41
  50. package/dist/error.mjs +0 -12
  51. package/dist/index.d.mts +0 -62
  52. package/dist/index.mjs +0 -25
  53. package/dist/meta-built-in.d.mts +0 -38
  54. package/dist/meta-built-in.mjs +0 -40
  55. package/dist/meta-utils.d.mts +0 -62
  56. package/dist/meta-utils.mjs +0 -33
  57. package/dist/meta.d.mts +0 -61
  58. package/dist/meta.mjs +0 -11
  59. package/dist/plugins/index.d.mts +0 -12
  60. package/dist/plugins/index.mjs +0 -8
  61. package/dist/plugins/request-validation.d.mts +0 -28
  62. package/dist/plugins/request-validation.mjs +0 -46
  63. package/dist/plugins/response-validation.d.mts +0 -15
  64. package/dist/plugins/response-validation.mjs +0 -53
  65. package/dist/procedure-client.d.mts +0 -10
  66. package/dist/procedure.d.mts +0 -36
  67. package/dist/procedure.mjs +0 -19
  68. package/dist/router-client.d.mts +0 -14
  69. package/dist/router-utils.d.mts +0 -34
  70. package/dist/router-utils.mjs +0 -67
  71. package/dist/router.d.mts +0 -42
  72. package/dist/schema-built-in.d.mts +0 -28
  73. package/dist/schema-built-in.mjs +0 -73
  74. package/dist/schema-utils.d.mts +0 -26
  75. package/dist/schema-utils.mjs +0 -29
  76. package/dist/schema.d.mts +0 -31
  77. /package/dist/{builder-variants.mjs → builder-variants.js} +0 -0
  78. /package/dist/{procedure-client.mjs → procedure-client.js} +0 -0
  79. /package/dist/{router-client.mjs → router-client.js} +0 -0
  80. /package/dist/{router.mjs → router.js} +0 -0
  81. /package/dist/{schema.mjs → schema.js} +0 -0
@@ -1,62 +0,0 @@
1
- import type { ErrorMap } from "./error.mjs";
2
- import type { AnyMetaPlugin, Meta, MetaPlugin } from "./meta.mjs";
3
- import type { AnySchema } from "./schema.mjs";
4
- export declare function resolveMetaPlugins<
5
- TInputSchema extends AnySchema,
6
- TOutputSchema extends AnySchema,
7
- TErrorMap extends ErrorMap
8
- >(baseMeta: Meta, existingPlugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[] | undefined, incomingPlugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[] | undefined): [meta: Meta, plugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[]];
9
- /**
10
- * Quickly defines a meta plugin factory and reader.
11
- *
12
- * @example Mark a procedure as requiring authentication and read it in middleware.
13
- * ```ts
14
- * interface AuthMeta {
15
- * required?: boolean
16
- * scope?: 'user' | 'admin'
17
- * }
18
- *
19
- * const [authMeta, getAuthMeta] = defineMeta(
20
- * 'auth',
21
- * (incoming: AuthMeta, current) => ({ ...current, ...incoming }),
22
- * )
23
- *
24
- * const deletePostContract = oc
25
- * .meta(authMeta({ required: true, scope: 'admin' }))
26
- * .input(z.object({ postId: z.string() }))
27
- * .output(z.object({ success: z.boolean() }))
28
- *
29
- * const authMiddleware = os.middleware(async ({ context, procedure, next }) => {
30
- * const auth = getAuthMeta(procedure)
31
- *
32
- * if (auth?.required && !context.user) {
33
- * throw new ORPCError('UNAUTHORIZED')
34
- * }
35
- *
36
- * if (auth?.scope === 'admin' && !context.user?.isAdmin) {
37
- * throw new ORPCError('FORBIDDEN')
38
- * }
39
- *
40
- * return next()
41
- * })
42
- * ```
43
- *
44
- * @param name - Unique key for storing this meta entry.
45
- * @param merge - Merges the existing value (or `undefined`) with the incoming value when applied multiple times.
46
- *
47
- * @returns A `[metaPlugin, getMeta]` tuple:
48
- * - `metaPlugin(metadata)` - Attaches metadata to a procedure under `name`.
49
- * - `getMeta(procedureOrLazy)` - Retrieves the metadata, or `undefined` if not set.
50
- *
51
- * @see {@link https://orpc.dev/docs/metadata | Metadata}
52
- */
53
- export declare function defineMeta<
54
- TName extends string,
55
- TData
56
- >(name: TName, merge: (incoming: TData, current: TData | undefined) => TData): [metaPlugin: (meta: TData) => AnyMetaPlugin & {
57
- name: TName;
58
- }, getMeta: (procedureOrLazy: {
59
- "~orpc": {
60
- meta: Meta;
61
- };
62
- }) => TData | undefined];
@@ -1,33 +0,0 @@
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
- export function defineMeta(name, merge) {
21
- const metaPlugin = (value) => ({
22
- name,
23
- init: (meta) => {
24
- const current = meta[name];
25
- return {
26
- ...meta,
27
- [name]: merge(value, current)
28
- };
29
- }
30
- });
31
- const getMeta = (procedureOrLazy) => procedureOrLazy["~orpc"].meta[name];
32
- return [metaPlugin, getMeta];
33
- }
package/dist/meta.d.mts DELETED
@@ -1,61 +0,0 @@
1
- import type { ErrorMap } from "./error.mjs";
2
- import type { AnySchema } from "./schema.mjs";
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<
13
- TInputSchema extends AnySchema,
14
- TOutputSchema extends AnySchema,
15
- TErrorMap extends ErrorMap
16
- > {
17
- __TInputSchema?: {
18
- type: TInputSchema;
19
- };
20
- __TOutputSchema?: {
21
- type: TOutputSchema;
22
- };
23
- __TErrorMap?: {
24
- type: TErrorMap;
25
- };
26
- }
27
- /**
28
- * A metadata plugin passed to `.meta(...)`.
29
- * Defines how metadata is initialized and merged, and can infer or restrict procedure types.
30
- *
31
- * @see {@link https://orpc.dev/docs/metadata | Metadata}
32
- */
33
- export interface MetaPlugin<
34
- TInputSchema extends AnySchema,
35
- TOutputSchema extends AnySchema,
36
- TErrorMap extends ErrorMap
37
- > {
38
- /** This only for types, so it should be optional */
39
- "~orpc"?: MetaPluginDefinition<TInputSchema, TOutputSchema, TErrorMap> | undefined;
40
- /** Unique name of the plugin, used for identification. */
41
- "name": string;
42
- /**
43
- * Runs once when this plugin is first added to the builder.
44
- * Use this to set up initial metadata values.
45
- */
46
- "init"?: (meta: Meta) => Meta;
47
- /**
48
- * Runs every time metadata is updated.
49
- * This is called for all plugins in the chain whenever a new plugin is added.
50
- */
51
- "apply"?: (meta: Meta) => Meta;
52
- }
53
- /**
54
- * A `MetaPlugin` with all type parameters relaxed to `any`.
55
- *
56
- * @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
57
- * @see {@link https://orpc.dev/docs/procedure | Procedure}
58
- */
59
- export type AnyMetaPlugin = MetaPlugin<any, any, any>;
60
- export declare function getHiddenMetaPlugins(container: unknown): AnyMetaPlugin[] | undefined;
61
- export declare function setHiddenMetaPlugins<T extends object>(container: T, metaPlugins: AnyMetaPlugin[]): void;
package/dist/meta.mjs DELETED
@@ -1,11 +0,0 @@
1
- import { isTypescriptObject } from "@orpc/shared";
2
- const HIDDEN_META_PLUGINS_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_HIDDEN_META_PLUGINS");
3
- export function getHiddenMetaPlugins(container) {
4
- if (!isTypescriptObject(container)) {
5
- return undefined;
6
- }
7
- return container[HIDDEN_META_PLUGINS_SYMBOL];
8
- }
9
- export function setHiddenMetaPlugins(container, metaPlugins) {
10
- container[HIDDEN_META_PLUGINS_SYMBOL] = metaPlugins;
11
- }
@@ -1,12 +0,0 @@
1
- export * from "./request-validation.mjs";
2
- export {
3
- /**
4
- * @deprecated Use `RequestValidationLinkPlugin` instead.
5
- */
6
- RequestValidationLinkPlugin as RequestValidationPlugin } from "./request-validation.mjs";
7
- export * from "./response-validation.mjs";
8
- export {
9
- /**
10
- * @deprecated Use `ResponseValidationLinkPlugin` instead.
11
- */
12
- ResponseValidationLinkPlugin as ResponseValidationPlugin } from "./response-validation.mjs";
@@ -1,8 +0,0 @@
1
- export * from "./request-validation.mjs";
2
- export {
3
-
4
- RequestValidationLinkPlugin as RequestValidationPlugin } from "./request-validation.mjs";
5
- export * from "./response-validation.mjs";
6
- export {
7
-
8
- ResponseValidationLinkPlugin as ResponseValidationPlugin } from "./response-validation.mjs";
@@ -1,28 +0,0 @@
1
- import type { ClientContext } from "@orpc/client";
2
- import type { StandardLinkOptions, StandardLinkPlugin } from "@orpc/client/standard";
3
- import type { RouterContract } from "../router.mjs";
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
- }
@@ -1,46 +0,0 @@
1
- import { ORPCError } from "@orpc/client";
2
- import { mergeTwoLevels, toArray } from "@orpc/shared";
3
- import { ValidationError } from "../error.mjs";
4
- import { getProcedureContractOrThrow } from "../router-utils.mjs";
5
-
6
- export class RequestValidationLinkPlugin {
7
- contract;
8
- name = "~request-validation";
9
- forwardValidatedInput;
10
- constructor(contract, options = {}) {
11
- this.contract = contract;
12
- this.forwardValidatedInput = options.forwardValidatedInput ?? false;
13
- }
14
- init(options) {
15
- return {
16
- ...options,
17
- interceptors: [...toArray(options.interceptors), async ({ next, ...interceptorOptions }) => {
18
- const procedure = getProcedureContractOrThrow(this.contract, interceptorOptions.path);
19
- const inputSchemas = toArray(procedure["~orpc"].inputSchemas);
20
- const originalInput = interceptorOptions.input;
21
- let currentInput = originalInput;
22
- for (const [index, schema] of inputSchemas.entries()) {
23
-
24
- const validating = index !== 0 ? mergeTwoLevels(originalInput, currentInput) : currentInput;
25
- const result = await schema["~standard"].validate(validating);
26
- if (result.issues) {
27
- throw new ORPCError("BAD_REQUEST", {
28
- message: "Input validation failed",
29
- data: { issues: result.issues },
30
- cause: new ValidationError({
31
- message: "Input validation failed",
32
- issues: result.issues,
33
- invalidData: validating
34
- })
35
- });
36
- }
37
- currentInput = index !== 0 ? mergeTwoLevels(currentInput, result.value) : result.value;
38
- }
39
- return this.forwardValidatedInput ? next({
40
- ...interceptorOptions,
41
- input: currentInput
42
- }) : next();
43
- }]
44
- };
45
- }
46
- }
@@ -1,15 +0,0 @@
1
- import type { ClientContext } from "@orpc/client";
2
- import type { StandardLinkOptions, StandardLinkPlugin } from "@orpc/client/standard";
3
- import type { RouterContract } from "../router.mjs";
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
- }
@@ -1,53 +0,0 @@
1
- import { ORPCError } from "@orpc/client";
2
- import { toArray } from "@orpc/shared";
3
- import { ValidationError } from "../error.mjs";
4
- import { reconcileORPCError } from "../error-utils.mjs";
5
- import { getProcedureContractOrThrow } from "../router-utils.mjs";
6
-
7
- export class ResponseValidationLinkPlugin {
8
- contract;
9
- name = "~response-validation";
10
- constructor(contract) {
11
- this.contract = contract;
12
- }
13
- init(options) {
14
- return {
15
- ...options,
16
- interceptors: [
17
- async ({ next, path }) => {
18
- const procedure = getProcedureContractOrThrow(this.contract, path);
19
- try {
20
- return await next();
21
- } catch (error) {
22
- if (error instanceof ORPCError) {
23
- throw await reconcileORPCError(procedure["~orpc"].errorMap, error);
24
- }
25
- throw error;
26
- }
27
- },
28
- ...toArray(options.interceptors),
29
- async ({ next, path }) => {
30
- const procedure = getProcedureContractOrThrow(this.contract, path);
31
- const outputSchemas = toArray(procedure["~orpc"].outputSchemas);
32
- let output = await next();
33
- for (let i = outputSchemas.length - 1; i >= 0; i--) {
34
- const schema = outputSchemas[i];
35
- const result = await schema["~standard"].validate(output);
36
- if (result.issues) {
37
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
38
- message: "Output validation failed",
39
- cause: new ValidationError({
40
- message: "Output validation failed",
41
- issues: result.issues,
42
- invalidData: output
43
- })
44
- });
45
- }
46
- output = result.value;
47
- }
48
- return output;
49
- }
50
- ]
51
- };
52
- }
53
- }
@@ -1,10 +0,0 @@
1
- import type { Client, ClientContext } from "@orpc/client";
2
- import type { ThrowableError } from "@orpc/shared";
3
- import type { ErrorMap, ORPCErrorFromErrorMap } from "./error.mjs";
4
- import type { AnySchema, InferSchemaInput, InferSchemaOutput } from "./schema.mjs";
5
- export type ProcedureContractClient<
6
- TClientContext extends ClientContext,
7
- TInputSchema extends AnySchema,
8
- TOutputSchema extends AnySchema,
9
- TErrorMap extends ErrorMap
10
- > = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ORPCErrorFromErrorMap<TErrorMap> | ThrowableError>;
@@ -1,36 +0,0 @@
1
- import type { ErrorMap } from "./error.mjs";
2
- import type { AnyMetaPlugin, Meta } from "./meta.mjs";
3
- import type { AnySchema } from "./schema.mjs";
4
- export interface ProcedureContractDefinition<
5
- TInputSchema extends AnySchema,
6
- TOutputSchema extends AnySchema,
7
- TErrorMap extends ErrorMap
8
- > {
9
- __TInputSchema?: {
10
- type: TInputSchema;
11
- };
12
- __TOutputSchema?: {
13
- type: TOutputSchema;
14
- };
15
- /**
16
- * Non-serializable should be optional
17
- */
18
- inputSchemas?: AnySchema[] | undefined;
19
- outputSchemas?: AnySchema[] | undefined;
20
- metaPlugins?: AnyMetaPlugin[] | undefined;
21
- errorMap: TErrorMap;
22
- meta: Meta;
23
- }
24
- export declare class ProcedureContract<
25
- TInputSchema extends AnySchema,
26
- TOutputSchema extends AnySchema,
27
- TErrorMap extends ErrorMap
28
- > {
29
- "~orpc": ProcedureContractDefinition<TInputSchema, TOutputSchema, TErrorMap>;
30
- constructor(def: ProcedureContractDefinition<TInputSchema, TOutputSchema, TErrorMap>);
31
- /**
32
- * Checks if the given instance satisfies the {@link ProcedureContract} class/interface.
33
- */
34
- static [Symbol.hasInstance](instance: unknown): boolean;
35
- }
36
- export type AnyProcedureContract = ProcedureContract<any, any, any>;
@@ -1,19 +0,0 @@
1
- import { getConstructor, isTypescriptObject } from "@orpc/shared";
2
- export class ProcedureContract {
3
- "~orpc";
4
- constructor(def) {
5
- this["~orpc"] = def;
6
- }
7
-
8
- static [Symbol.hasInstance](instance) {
9
- if (this !== ProcedureContract) {
10
-
11
- return Function.prototype[Symbol.hasInstance].call(this, instance);
12
- }
13
- const constructor = getConstructor(instance);
14
- if (constructor === ProcedureContract) {
15
- return true;
16
- }
17
- return isTypescriptObject(instance) && isTypescriptObject(instance["~orpc"]) && isTypescriptObject(instance["~orpc"].errorMap) && isTypescriptObject(instance["~orpc"].meta) && (instance["~orpc"].inputSchemas === undefined || Array.isArray(instance["~orpc"].inputSchemas)) && (instance["~orpc"].outputSchemas === undefined || Array.isArray(instance["~orpc"].outputSchemas));
18
- }
19
- }
@@ -1,14 +0,0 @@
1
- import type { ClientContext } from "@orpc/client";
2
- import type { ProcedureContract } from "./procedure.mjs";
3
- import type { ProcedureContractClient } from "./procedure-client.mjs";
4
- import type { RouterContract } from "./router.mjs";
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<
12
- TRouter extends RouterContract,
13
- TClientContext extends ClientContext = object
14
- > = 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,34 +0,0 @@
1
- import type { ErrorMap } from "./error.mjs";
2
- import type { MergedErrorMap } from "./error-utils.mjs";
3
- import type { AnyMetaPlugin, Meta } from "./meta.mjs";
4
- import type { AnyProcedureContract } from "./procedure.mjs";
5
- import type { RouterContract } from "./router.mjs";
6
- import { ProcedureContract } from "./procedure.mjs";
7
- export type AugmentedContractRouter<
8
- T extends RouterContract,
9
- TErrorMap extends ErrorMap
10
- > = 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 };
11
- export interface AugmentContractRouterOptions<TErrorMap extends ErrorMap> {
12
- meta: Meta;
13
- metaPlugins?: AnyMetaPlugin[] | undefined;
14
- errorMap: TErrorMap;
15
- }
16
- /**
17
- * Add capabilities without changing identity of the router contract
18
- */
19
- export declare function augmentContractRouter<
20
- T extends RouterContract,
21
- TErrorMap extends ErrorMap
22
- >(router: T, options: AugmentContractRouterOptions<TErrorMap>): AugmentedContractRouter<T, TErrorMap>;
23
- export declare function getRouterContract(router: RouterContract, path: readonly string[]): RouterContract | undefined;
24
- export declare function getProcedureContractOrThrow(router: RouterContract, path: readonly string[]): AnyProcedureContract;
25
- /**
26
- * Minifies a router contract so it can be safely exported to the client
27
- * without exposing internal logic.
28
- *
29
- * @remarks
30
- * **Note**: Only the metadata needed by the client is preserved; all other data is stripped out.
31
- *
32
- * @see {@link https://orpc.dev/docs/contract/router | Router Contract}
33
- */
34
- export declare function minifyRouterContract(router: RouterContract): RouterContract;
@@ -1,67 +0,0 @@
1
- import { getOwn, isTypescriptObject } from "@orpc/shared";
2
- import { mergeErrorMap } from "./error-utils.mjs";
3
- import { resolveMetaPlugins } from "./meta-utils.mjs";
4
- import { ProcedureContract } from "./procedure.mjs";
5
-
6
- export function augmentContractRouter(router, options) {
7
- if (router instanceof ProcedureContract) {
8
- const [meta, metaPlugins] = resolveMetaPlugins(options.meta, options.metaPlugins, router["~orpc"].metaPlugins);
9
- const enhanced = new ProcedureContract({
10
- ...router["~orpc"],
11
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
12
- meta,
13
- metaPlugins
14
- });
15
- return enhanced;
16
- }
17
- if (!isTypescriptObject(router)) {
18
- return router;
19
- }
20
- const enhanced = {};
21
- for (const key of Object.keys(router)) {
22
- enhanced[key] = augmentContractRouter(router[key], options);
23
- }
24
- return enhanced;
25
- }
26
- export function getRouterContract(router, path) {
27
- let current = router;
28
- for (let i = 0; i < path.length; i++) {
29
- const segment = path[i];
30
- if (!isTypescriptObject(current)) {
31
- return undefined;
32
- }
33
- if (current instanceof ProcedureContract) {
34
- return undefined;
35
- }
36
- current = getOwn(current, segment);
37
- }
38
- if (!isTypescriptObject(current)) {
39
- return undefined;
40
- }
41
- return current;
42
- }
43
- export function getProcedureContractOrThrow(router, path) {
44
- const procedure = getRouterContract(router, path);
45
- if (!(procedure instanceof ProcedureContract)) {
46
- throw new TypeError(`No valid procedure found at path "${path.join(".")}", this may happen when the router contract is not properly configured.`);
47
- }
48
- return procedure;
49
- }
50
-
51
- export function minifyRouterContract(router) {
52
- if (router instanceof ProcedureContract) {
53
- const procedure = { "~orpc": {
54
- errorMap: {},
55
- meta: router["~orpc"].meta
56
- } };
57
- return procedure;
58
- }
59
- if (!isTypescriptObject(router)) {
60
- return router;
61
- }
62
- const json = {};
63
- for (const [key, child] of Object.entries(router)) {
64
- json[key] = minifyRouterContract(child);
65
- }
66
- return json;
67
- }
package/dist/router.d.mts DELETED
@@ -1,42 +0,0 @@
1
- import type { ThrowableError } from "@orpc/shared";
2
- import type { ORPCErrorFromErrorMap } from "./error.mjs";
3
- import type { AnyProcedureContract, ProcedureContract } from "./procedure.mjs";
4
- import type { InferSchemaInput, InferSchemaOutput } from "./schema.mjs";
5
- /**
6
- * A router contract: a single procedure contract or a nested record of them.
7
- *
8
- * @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
9
- */
10
- export type RouterContract = AnyProcedureContract | {
11
- [k: string]: RouterContract;
12
- };
13
- /**
14
- * Infer the input types for each procedure-contract, preserving the router-contract shape.
15
- *
16
- * @see {@link https://orpc.dev/docs/contract/router#infer-router-contract-inputs | Router Contract - Infer Router Contract Inputs}
17
- */
18
- export type InferRouterContractInputs<T extends RouterContract> = T extends ProcedureContract<infer UInputSchema, any, any> ? InferSchemaInput<UInputSchema> : { [K in keyof T]: T[K] extends RouterContract ? InferRouterContractInputs<T[K]> : never };
19
- /**
20
- * Infer the output types for each procedure-contract, preserving the router-contract shape.
21
- *
22
- * @see {@link https://orpc.dev/docs/contract/router#infer-router-contract-outputs | Router Contract - Infer Router Contract Outputs}
23
- */
24
- export type InferRouterContractOutputs<T extends RouterContract> = T extends ProcedureContract<any, infer UOutputSchema, any> ? InferSchemaOutput<UOutputSchema> : { [K in keyof T]: T[K] extends RouterContract ? InferRouterContractOutputs<T[K]> : never };
25
- /**
26
- * Infer the union of error maps defined across the entire router-contract.
27
- *
28
- * @see {@link https://orpc.dev/docs/contract/router#infer-router-contract-error-map | Router Contract - Infer Router Contract Error Map}
29
- */
30
- export type InferRouterContractErrorMap<T extends RouterContract> = T extends ProcedureContract<any, any, infer UErrorMap> ? UErrorMap : { [K in keyof T]: T[K] extends RouterContract ? InferRouterContractErrorMap<T[K]> : never }[keyof T];
31
- /**
32
- * Infer the union of throwable errors for entire router-contract.
33
- *
34
- * @see {@link https://orpc.dev/docs/contract/router#infer-router-contract-error | Router Contract - Infer Router Contract Error}
35
- */
36
- export type InferRouterContractError<T extends RouterContract> = T extends ProcedureContract<any, any, infer UErrorMap> ? ORPCErrorFromErrorMap<UErrorMap> | ThrowableError : { [K in keyof T]: T[K] extends RouterContract ? InferRouterContractError<T[K]> : never }[keyof T];
37
- /**
38
- * Infer throwable errors for each procedure-contract, preserving the router-contract shape.
39
- *
40
- * @see {@link https://orpc.dev/docs/contract/router#infer-router-contract-errors | Router Contract - Infer Router Contract Errors}
41
- */
42
- export type InferRouterContractErrors<T extends RouterContract> = T extends ProcedureContract<any, any, infer UErrorMap> ? ORPCErrorFromErrorMap<UErrorMap> | ThrowableError : { [K in keyof T]: T[K] extends RouterContract ? InferRouterContractErrors<T[K]> : never };
@@ -1,28 +0,0 @@
1
- import type { AsyncIteratorClass } from "@orpc/shared";
2
- import type { AnySchema, Schema } from "./schema.mjs";
3
- export interface AsyncIteratorObjectSchemaDetails {
4
- yieldSchema: AnySchema;
5
- returnSchema?: AnySchema | undefined;
6
- }
7
- /**
8
- * Defines a schema for an AsyncIteratorObject, validating each yielded value
9
- * (and optionally the return value) with the given schemas.
10
- *
11
- * @see {@link https://orpc.dev/docs/async-iterator-object | AsyncIteratorObject (SSE)}
12
- */
13
- export declare function asyncIteratorObject<
14
- TYieldIn,
15
- TYieldOut,
16
- TReturnIn = unknown,
17
- TReturnOut = unknown
18
- >(yieldSchema: Schema<TYieldIn, TYieldOut>, returnSchema?: Schema<TReturnIn, TReturnOut>): Schema<AsyncIteratorObject<TYieldIn, TReturnIn, void>, AsyncIteratorClass<TYieldOut, TReturnOut, void>>;
19
- export declare function getAsyncIteratorObjectSchemaDetails(schema: AnySchema | undefined): undefined | AsyncIteratorObjectSchemaDetails;
20
- export interface AsyncIteratorObjectSchemasDetails {
21
- yieldSchemas: AnySchema[];
22
- returnSchemas: AnySchema[];
23
- }
24
- /**
25
- * Collects the yield and return schemas of multiple schemas, such as the `.output` schemas of a procedure,
26
- * or returns `undefined` when there are none or any of them does not describe an AsyncIteratorObject.
27
- */
28
- export declare function getAsyncIteratorObjectSchemasDetails(schemas: readonly AnySchema[] | undefined): undefined | AsyncIteratorObjectSchemasDetails;
@@ -1,73 +0,0 @@
1
- import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from "@orpc/client";
2
- import { isAsyncIteratorObject, ORPC_NAME } from "@orpc/shared";
3
- import { ValidationError } from "./error.mjs";
4
- const ASYNC_ITERATOR_OBJECT_SCHEMA_DETAILS_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_ASYNC_ITERATOR_OBJECT_SCHEMA_DETAILS");
5
-
6
- export function asyncIteratorObject(yieldSchema, returnSchema) {
7
- return { "~standard": {
8
- [ASYNC_ITERATOR_OBJECT_SCHEMA_DETAILS_SYMBOL]: {
9
- yieldSchema,
10
- returnSchema
11
- },
12
- vendor: ORPC_NAME,
13
- version: 1,
14
- validate(iterator) {
15
- if (!isAsyncIteratorObject(iterator)) {
16
- return { issues: [{
17
- message: "Expect AsyncIteratorObject",
18
- path: []
19
- }] };
20
- }
21
- const mapped = wrapAsyncIteratorPreservingEventMeta(iterator, { async mapResult(result) {
22
- const schema = result.done ? returnSchema : yieldSchema;
23
- if (!schema) {
24
- return result;
25
- }
26
- const validated = await schema["~standard"].validate(result.value);
27
- if (validated.issues) {
28
- throw new ORPCError("ASYNC_ITERATOR_OBJECT_VALIDATION_FAILED", {
29
- message: "AsyncIteratorObject validation failed",
30
- cause: new ValidationError({
31
- issues: validated.issues,
32
- message: "AsyncIteratorObject validation failed",
33
- invalidData: result.value
34
- })
35
- });
36
- }
37
- return {
38
- done: result.done,
39
- value: validated.value
40
- };
41
- } });
42
- return { value: mapped };
43
- }
44
- } };
45
- }
46
- export function getAsyncIteratorObjectSchemaDetails(schema) {
47
- if (schema === undefined) {
48
- return undefined;
49
- }
50
- return schema["~standard"][ASYNC_ITERATOR_OBJECT_SCHEMA_DETAILS_SYMBOL];
51
- }
52
-
53
- export function getAsyncIteratorObjectSchemasDetails(schemas) {
54
- if (!schemas || schemas.length === 0) {
55
- return undefined;
56
- }
57
- const yieldSchemas = [];
58
- const returnSchemas = [];
59
- for (const schema of schemas) {
60
- const details = getAsyncIteratorObjectSchemaDetails(schema);
61
- if (!details) {
62
- return undefined;
63
- }
64
- yieldSchemas.push(details.yieldSchema);
65
- if (details.returnSchema) {
66
- returnSchemas.push(details.returnSchema);
67
- }
68
- }
69
- return {
70
- yieldSchemas,
71
- returnSchemas
72
- };
73
- }