@orpc/client 0.0.0-next.ee0aeaf → 0.0.0-next.f99e554

Sign up to get free protection for your applications and to get access to all the features.
package/dist/fetch.js ADDED
@@ -0,0 +1,87 @@
1
+ // src/adapters/fetch/orpc-link.ts
2
+ import { ORPCPayloadCodec } from "@orpc/server/fetch";
3
+ import { ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE, trim } from "@orpc/shared";
4
+ import { ORPCError } from "@orpc/shared/error";
5
+ var ORPCLink = class {
6
+ fetch;
7
+ payloadCodec;
8
+ maxURLLength;
9
+ fallbackMethod;
10
+ getMethod;
11
+ getHeaders;
12
+ url;
13
+ constructor(options) {
14
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
15
+ this.payloadCodec = options.payloadCodec ?? new ORPCPayloadCodec();
16
+ this.maxURLLength = options.maxURLLength ?? 2083;
17
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
18
+ this.url = options.url;
19
+ this.getMethod = async (path, input, context) => {
20
+ return await options.method?.(path, input, context) ?? this.fallbackMethod;
21
+ };
22
+ this.getHeaders = async (path, input, context) => {
23
+ return new Headers(await options.headers?.(path, input, context));
24
+ };
25
+ }
26
+ async call(path, input, options) {
27
+ const clientContext = options.context;
28
+ const encoded = await this.encode(path, input, options);
29
+ const response = await this.fetch(encoded.url, {
30
+ method: encoded.method,
31
+ headers: encoded.headers,
32
+ body: encoded.body,
33
+ signal: options.signal
34
+ }, clientContext);
35
+ const decoded = await this.payloadCodec.decode(response);
36
+ if (!response.ok) {
37
+ const error = ORPCError.fromJSON(decoded) ?? new ORPCError({
38
+ status: response.status,
39
+ code: "INTERNAL_SERVER_ERROR",
40
+ message: "Internal server error",
41
+ cause: decoded
42
+ });
43
+ throw error;
44
+ }
45
+ return decoded;
46
+ }
47
+ async encode(path, input, options) {
48
+ const clientContext = options.context;
49
+ const expectMethod = await this.getMethod(path, input, clientContext);
50
+ const methods = /* @__PURE__ */ new Set([expectMethod, this.fallbackMethod]);
51
+ const baseHeaders = await this.getHeaders(path, input, clientContext);
52
+ const baseUrl = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
53
+ baseHeaders.append(ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE);
54
+ for (const method of methods) {
55
+ const url = new URL(baseUrl);
56
+ const headers = new Headers(baseHeaders);
57
+ const encoded = this.payloadCodec.encode(input, method, this.fallbackMethod);
58
+ if (encoded.query) {
59
+ for (const [key, value] of encoded.query.entries()) {
60
+ url.searchParams.append(key, value);
61
+ }
62
+ }
63
+ if (url.toString().length > this.maxURLLength) {
64
+ continue;
65
+ }
66
+ if (encoded.headers) {
67
+ for (const [key, value] of encoded.headers.entries()) {
68
+ headers.append(key, value);
69
+ }
70
+ }
71
+ return {
72
+ url,
73
+ headers,
74
+ method: encoded.method,
75
+ body: encoded.body
76
+ };
77
+ }
78
+ throw new ORPCError({
79
+ code: "BAD_REQUEST",
80
+ message: "Cannot encode the request, please check the url length or payload."
81
+ });
82
+ }
83
+ };
84
+ export {
85
+ ORPCLink
86
+ };
87
+ //# sourceMappingURL=fetch.js.map
package/dist/index.js CHANGED
@@ -1,86 +1,39 @@
1
- // src/procedure.ts
2
- import { ORPC_PROTOCOL_HEADER, ORPC_PROTOCOL_VALUE, trim } from "@orpc/shared";
3
- import { ORPCError } from "@orpc/shared/error";
4
- import { ORPCDeserializer, ORPCSerializer } from "@orpc/transformer";
5
- var serializer = new ORPCSerializer();
6
- var deserializer = new ORPCDeserializer();
7
- function createProcedureClient(options) {
8
- const client = async (...args) => {
9
- const [input, callerOptions] = args;
10
- const fetch_ = options.fetch ?? fetch;
11
- const url = `${trim(options.baseURL, "/")}/${options.path.map(encodeURIComponent).join("/")}`;
12
- const headers = new Headers({
13
- [ORPC_PROTOCOL_HEADER]: ORPC_PROTOCOL_VALUE
14
- });
15
- let customHeaders = await options.headers?.(input);
16
- customHeaders = customHeaders instanceof Headers ? customHeaders : new Headers(customHeaders);
17
- for (const [key, value] of customHeaders.entries()) {
18
- headers.append(key, value);
19
- }
20
- const serialized = serializer.serialize(input);
21
- for (const [key, value] of serialized.headers.entries()) {
22
- headers.append(key, value);
23
- }
24
- const response = await fetch_(url, {
25
- method: "POST",
26
- headers,
27
- body: serialized.body,
28
- signal: callerOptions?.signal
29
- });
30
- const json = await (async () => {
31
- try {
32
- return await deserializer.deserialize(response);
33
- } catch (e) {
34
- throw new ORPCError({
35
- code: "INTERNAL_SERVER_ERROR",
36
- message: "Cannot parse response.",
37
- cause: e
38
- });
1
+ // src/client.ts
2
+ function createORPCClient(link, options) {
3
+ const path = options?.path ?? [];
4
+ const procedureClient = async (...[input, options2]) => {
5
+ return await link.call(path, input, options2 ?? {});
6
+ };
7
+ const recursive = new Proxy(procedureClient, {
8
+ get(target, key) {
9
+ if (typeof key !== "string") {
10
+ return Reflect.get(target, key);
39
11
  }
40
- })();
41
- if (!response.ok) {
42
- throw ORPCError.fromJSON(json) ?? new ORPCError({
43
- status: response.status,
44
- code: "INTERNAL_SERVER_ERROR",
45
- message: "Internal server error"
12
+ return createORPCClient(link, {
13
+ ...options,
14
+ path: [...path, key]
46
15
  });
47
16
  }
48
- return json;
49
- };
50
- return client;
17
+ });
18
+ return recursive;
51
19
  }
52
20
 
53
- // src/router.ts
54
- function createRouterClient(options) {
55
- const path = options?.path ?? [];
56
- const client = new Proxy(
57
- createProcedureClient({
58
- baseURL: options.baseURL,
59
- fetch: options.fetch,
60
- headers: options.headers,
61
- path
62
- }),
63
- {
64
- get(target, key) {
65
- if (typeof key !== "string") {
66
- return Reflect.get(target, key);
67
- }
68
- return createRouterClient({
69
- ...options,
70
- path: [...path, key]
71
- });
72
- }
73
- }
74
- );
75
- return client;
76
- }
21
+ // src/dynamic-link.ts
22
+ var DynamicLink = class {
23
+ constructor(linkResolver) {
24
+ this.linkResolver = linkResolver;
25
+ }
26
+ async call(path, input, options) {
27
+ const resolvedLink = await this.linkResolver(path, input, options.context);
28
+ const output = await resolvedLink.call(path, input, options);
29
+ return output;
30
+ }
31
+ };
77
32
 
78
33
  // src/index.ts
79
34
  export * from "@orpc/shared/error";
80
- var createORPCClient = createRouterClient;
81
35
  export {
82
- createORPCClient,
83
- createProcedureClient,
84
- createRouterClient
36
+ DynamicLink,
37
+ createORPCClient
85
38
  };
86
39
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ export * from './orpc-link';
2
+ export * from './types';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,47 @@
1
+ import type { HTTPMethod } from '@orpc/contract';
2
+ import type { ProcedureClientOptions } from '@orpc/server';
3
+ import type { Promisable } from '@orpc/shared';
4
+ import type { ClientLink } from '../../types';
5
+ import type { FetchWithContext } from './types';
6
+ import { type PublicORPCPayloadCodec } from '@orpc/server/fetch';
7
+ export interface ORPCLinkOptions<TClientContext> {
8
+ /**
9
+ * Base url for all requests.
10
+ */
11
+ url: string;
12
+ /**
13
+ * The maximum length of the URL.
14
+ *
15
+ * @default 2083
16
+ */
17
+ maxURLLength?: number;
18
+ /**
19
+ * The method used to make the request.
20
+ *
21
+ * @default 'POST'
22
+ */
23
+ method?: (path: readonly string[], input: unknown, context: TClientContext) => Promisable<HTTPMethod | undefined>;
24
+ /**
25
+ * The method to use when the payload cannot safely pass to the server with method return from method function.
26
+ * Do not use GET as fallback method, it's very dangerous.
27
+ *
28
+ * @default 'POST'
29
+ */
30
+ fallbackMethod?: HTTPMethod;
31
+ headers?: (path: readonly string[], input: unknown, context: TClientContext) => Promisable<Headers | Record<string, string>>;
32
+ fetch?: FetchWithContext<TClientContext>;
33
+ payloadCodec?: PublicORPCPayloadCodec;
34
+ }
35
+ export declare class ORPCLink<TClientContext> implements ClientLink<TClientContext> {
36
+ private readonly fetch;
37
+ private readonly payloadCodec;
38
+ private readonly maxURLLength;
39
+ private readonly fallbackMethod;
40
+ private readonly getMethod;
41
+ private readonly getHeaders;
42
+ private readonly url;
43
+ constructor(options: ORPCLinkOptions<TClientContext>);
44
+ call(path: readonly string[], input: unknown, options: ProcedureClientOptions<TClientContext>): Promise<unknown>;
45
+ private encode;
46
+ }
47
+ //# sourceMappingURL=orpc-link.d.ts.map
@@ -0,0 +1,4 @@
1
+ export interface FetchWithContext<TClientContext> {
2
+ (input: RequestInfo | URL, init: RequestInit | undefined, context: TClientContext): Promise<Response>;
3
+ }
4
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,11 @@
1
+ import type { ContractRouter } from '@orpc/contract';
2
+ import type { ANY_ROUTER, RouterClient } from '@orpc/server';
3
+ import type { ClientLink } from './types';
4
+ export interface createORPCClientOptions {
5
+ /**
6
+ * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
7
+ */
8
+ path?: string[];
9
+ }
10
+ export declare function createORPCClient<TRouter extends ANY_ROUTER | ContractRouter, TClientContext = unknown>(link: ClientLink<TClientContext>, options?: createORPCClientOptions): RouterClient<TRouter, TClientContext>;
11
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,13 @@
1
+ import type { ProcedureClientOptions } from '@orpc/server';
2
+ import type { Promisable } from '@orpc/shared';
3
+ import type { ClientLink } from './types';
4
+ /**
5
+ * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
6
+ * based on the request path, input, and context.
7
+ */
8
+ export declare class DynamicLink<TClientContext> implements ClientLink<TClientContext> {
9
+ private readonly linkResolver;
10
+ constructor(linkResolver: (path: readonly string[], input: unknown, context: TClientContext) => Promisable<ClientLink<TClientContext>>);
11
+ call(path: readonly string[], input: unknown, options: ProcedureClientOptions<TClientContext>): Promise<unknown>;
12
+ }
13
+ //# sourceMappingURL=dynamic-link.d.ts.map
@@ -1,7 +1,6 @@
1
1
  /** unnoq */
2
- import { createRouterClient } from './router';
3
- export * from './procedure';
4
- export * from './router';
2
+ export * from './client';
3
+ export * from './dynamic-link';
4
+ export * from './types';
5
5
  export * from '@orpc/shared/error';
6
- export declare const createORPCClient: typeof createRouterClient;
7
6
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ import type { ProcedureClientOptions } from '@orpc/server';
2
+ export interface ClientLink<TClientContext> {
3
+ call: (path: readonly string[], input: unknown, options: ProcedureClientOptions<TClientContext>) => Promise<unknown>;
4
+ }
5
+ //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/client",
3
3
  "type": "module",
4
- "version": "0.0.0-next.ee0aeaf",
4
+ "version": "0.0.0-next.f99e554",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -19,6 +19,11 @@
19
19
  "import": "./dist/index.js",
20
20
  "default": "./dist/index.js"
21
21
  },
22
+ "./fetch": {
23
+ "types": "./dist/src/adapters/fetch/index.d.ts",
24
+ "import": "./dist/fetch.js",
25
+ "default": "./dist/fetch.js"
26
+ },
22
27
  "./🔒/*": {
23
28
  "types": "./dist/src/*.d.ts"
24
29
  }
@@ -29,19 +34,18 @@
29
34
  "dist"
30
35
  ],
31
36
  "peerDependencies": {
32
- "@orpc/contract": "0.0.0-next.ee0aeaf",
33
- "@orpc/server": "0.0.0-next.ee0aeaf"
37
+ "@orpc/contract": "0.0.0-next.f99e554"
34
38
  },
35
39
  "dependencies": {
36
- "@orpc/shared": "0.0.0-next.ee0aeaf",
37
- "@orpc/transformer": "0.0.0-next.ee0aeaf"
40
+ "@orpc/server": "0.0.0-next.f99e554",
41
+ "@orpc/shared": "0.0.0-next.f99e554"
38
42
  },
39
43
  "devDependencies": {
40
44
  "zod": "^3.24.1",
41
- "@orpc/openapi": "0.0.0-next.ee0aeaf"
45
+ "@orpc/openapi": "0.0.0-next.f99e554"
42
46
  },
43
47
  "scripts": {
44
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
48
+ "build": "tsup --clean --sourcemap --entry.index=src/index.ts --entry.fetch=src/adapters/fetch/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
45
49
  "build:watch": "pnpm run build --watch",
46
50
  "type:check": "tsc -b"
47
51
  }
@@ -1,24 +0,0 @@
1
- import type { Caller } from '@orpc/server';
2
- import type { Promisable } from '@orpc/shared';
3
- export interface CreateProcedureClientOptions {
4
- /**
5
- * The base url of the server.
6
- */
7
- baseURL: string;
8
- /**
9
- * The fetch function used to make the request.
10
- * @default global fetch
11
- */
12
- fetch?: typeof fetch;
13
- /**
14
- * The headers used to make the request.
15
- * Invoked before the request is made.
16
- */
17
- headers?: (input: unknown) => Promisable<Headers | Record<string, string>>;
18
- /**
19
- * The path of the procedure on server.
20
- */
21
- path: string[];
22
- }
23
- export declare function createProcedureClient<TInput, TOutput>(options: CreateProcedureClientOptions): Caller<TInput, TOutput>;
24
- //# sourceMappingURL=procedure.d.ts.map
@@ -1,9 +0,0 @@
1
- import type { ContractProcedure, ContractRouter, SchemaInput, SchemaOutput } from '@orpc/contract';
2
- import type { Caller, Lazy, Procedure, Router } from '@orpc/server';
3
- import type { SetOptional } from '@orpc/shared';
4
- import type { CreateProcedureClientOptions } from './procedure';
5
- export type RouterClient<T extends Router<any> | ContractRouter> = {
6
- [K in keyof T]: T[K] extends ContractProcedure<infer UInputSchema, infer UOutputSchema> | Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> | Lazy<Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput>> ? Caller<SchemaInput<UInputSchema>, SchemaOutput<UOutputSchema, UFuncOutput>> : T[K] extends Router<any> | ContractRouter ? RouterClient<T[K]> : never;
7
- };
8
- export declare function createRouterClient<T extends Router<any> | ContractRouter>(options: SetOptional<CreateProcedureClientOptions, 'path'>): RouterClient<T>;
9
- //# sourceMappingURL=router.d.ts.map