@orpc/shared 0.0.0-next.e7b4f63 → 0.0.0-next.e7ee5a9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/shared">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fshared?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
+
24
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
25
+
26
+ ---
27
+
28
+ ## Highlights
29
+
30
+ - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
+ - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
+ - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
+ - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
+ - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
+ - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
+ - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
+ - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
+ - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
+ - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
+ - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
+ - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
+ - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
+ - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
+ - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
+ - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
46
+
47
+ ## Documentation
48
+
49
+ You can find the full documentation [here](https://orpc.unnoq.com).
50
+
51
+ ## Packages
52
+
53
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
+ - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
+ - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
60
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
61
+
62
+ ## `@orpc/shared`
63
+
64
+ Provides shared utilities for oRPC packages.
65
+
66
+ ## License
67
+
68
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,85 @@
1
+ import { Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
+ export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
4
+
5
+ type AnyFunction = (...args: any[]) => any;
6
+ declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
7
+
8
+ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
9
+ [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
10
+ };
11
+
12
+ declare function toError(error: unknown): Error;
13
+
14
+ type InterceptableOptions = Record<string, any>;
15
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
16
+ next(options?: TOptions): Promise<TResult>;
17
+ };
18
+ type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult>) => Promise<TResult> & {
19
+ __error?: {
20
+ type: TError;
21
+ };
22
+ };
23
+ /**
24
+ * Can used for interceptors or middlewares
25
+ */
26
+ declare function onStart<TOptions extends {
27
+ next(): any;
28
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
29
+ /**
30
+ * Can used for interceptors or middlewares
31
+ */
32
+ declare function onSuccess<TOptions extends {
33
+ next(): any;
34
+ }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
35
+ /**
36
+ * Can used for interceptors or middlewares
37
+ */
38
+ declare function onError<TError, TOptions extends {
39
+ next(): any;
40
+ }, TRest extends any[]>(callback: NoInfer<(error: TError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
41
+ __error?: {
42
+ type: TError;
43
+ };
44
+ };
45
+ type OnFinishState<TResult, TError> = [TResult, undefined, 'success'] | [undefined, TError, 'error'];
46
+ /**
47
+ * Can used for interceptors or middlewares
48
+ */
49
+ declare function onFinish<TError, TOptions extends {
50
+ next(): any;
51
+ }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, TError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
52
+ __error?: {
53
+ type: TError;
54
+ };
55
+ };
56
+ declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
57
+
58
+ declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
59
+
60
+ declare function parseEmptyableJSON(text: string | null | undefined): unknown;
61
+ declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
62
+
63
+ type Segment = string | number;
64
+ declare function set(root: unknown, segments: Readonly<Segment[]>, value: unknown): unknown;
65
+ declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown;
66
+ declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
67
+ maps: Segment[][];
68
+ values: unknown[];
69
+ };
70
+ /**
71
+ * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
72
+ */
73
+ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
74
+ /**
75
+ * Check if the value satisfy a `object` type in typescript
76
+ */
77
+ declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
78
+
79
+ type MaybeOptionalOptions<TOptions> = [options: TOptions] | (Record<never, never> extends TOptions ? [] : never);
80
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
81
+
82
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
83
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
84
+
85
+ export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type Segment, type SetOptional, type Value, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
@@ -0,0 +1,85 @@
1
+ import { Promisable } from 'type-fest';
2
+ export { IsEqual, IsNever, PartialDeep, Promisable } from 'type-fest';
3
+ export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
4
+
5
+ type AnyFunction = (...args: any[]) => any;
6
+ declare function once<T extends () => any>(fn: T): () => ReturnType<T>;
7
+
8
+ type OmitChainMethodDeep<T extends object, K extends keyof any> = {
9
+ [P in keyof Omit<T, K>]: T[P] extends AnyFunction ? ((...args: Parameters<T[P]>) => OmitChainMethodDeep<ReturnType<T[P]>, K>) : T[P];
10
+ };
11
+
12
+ declare function toError(error: unknown): Error;
13
+
14
+ type InterceptableOptions = Record<string, any>;
15
+ type InterceptorOptions<TOptions extends InterceptableOptions, TResult> = Omit<TOptions, 'next'> & {
16
+ next(options?: TOptions): Promise<TResult>;
17
+ };
18
+ type Interceptor<TOptions extends InterceptableOptions, TResult, TError> = (options: InterceptorOptions<TOptions, TResult>) => Promise<TResult> & {
19
+ __error?: {
20
+ type: TError;
21
+ };
22
+ };
23
+ /**
24
+ * Can used for interceptors or middlewares
25
+ */
26
+ declare function onStart<TOptions extends {
27
+ next(): any;
28
+ }, TRest extends any[]>(callback: NoInfer<(options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
29
+ /**
30
+ * Can used for interceptors or middlewares
31
+ */
32
+ declare function onSuccess<TOptions extends {
33
+ next(): any;
34
+ }, TRest extends any[]>(callback: NoInfer<(result: Awaited<ReturnType<TOptions['next']>>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>>;
35
+ /**
36
+ * Can used for interceptors or middlewares
37
+ */
38
+ declare function onError<TError, TOptions extends {
39
+ next(): any;
40
+ }, TRest extends any[]>(callback: NoInfer<(error: TError, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
41
+ __error?: {
42
+ type: TError;
43
+ };
44
+ };
45
+ type OnFinishState<TResult, TError> = [TResult, undefined, 'success'] | [undefined, TError, 'error'];
46
+ /**
47
+ * Can used for interceptors or middlewares
48
+ */
49
+ declare function onFinish<TError, TOptions extends {
50
+ next(): any;
51
+ }, TRest extends any[]>(callback: NoInfer<(state: OnFinishState<Awaited<ReturnType<TOptions['next']>>, TError>, options: TOptions, ...rest: TRest) => Promisable<void>>): (options: TOptions, ...rest: TRest) => Promise<Awaited<ReturnType<TOptions['next']>>> & {
52
+ __error?: {
53
+ type: TError;
54
+ };
55
+ };
56
+ declare function intercept<TOptions extends InterceptableOptions, TResult, TError>(interceptors: Interceptor<TOptions, TResult, TError>[], options: NoInfer<TOptions>, main: NoInfer<(options: TOptions) => Promisable<TResult>>): Promise<TResult>;
57
+
58
+ declare function isAsyncIteratorObject(maybe: unknown): maybe is AsyncIteratorObject<any, any, any>;
59
+
60
+ declare function parseEmptyableJSON(text: string | null | undefined): unknown;
61
+ declare function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string;
62
+
63
+ type Segment = string | number;
64
+ declare function set(root: unknown, segments: Readonly<Segment[]>, value: unknown): unknown;
65
+ declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown;
66
+ declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
67
+ maps: Segment[][];
68
+ values: unknown[];
69
+ };
70
+ /**
71
+ * Check if the value is an object even it created by `Object.create(null)` or more tricky way.
72
+ */
73
+ declare function isObject(value: unknown): value is Record<PropertyKey, unknown>;
74
+ /**
75
+ * Check if the value satisfy a `object` type in typescript
76
+ */
77
+ declare function isTypescriptObject(value: unknown): value is object & Record<PropertyKey, unknown>;
78
+
79
+ type MaybeOptionalOptions<TOptions> = [options: TOptions] | (Record<never, never> extends TOptions ? [] : never);
80
+ type SetOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
81
+
82
+ type Value<T, TArgs extends any[] = []> = T | ((...args: TArgs) => Promisable<T>);
83
+ declare function value<T, TArgs extends any[]>(value: Value<T, TArgs>, ...args: NoInfer<TArgs>): Promise<T extends Value<infer U, any> ? U : never>;
84
+
85
+ export { type AnyFunction, type InterceptableOptions, type Interceptor, type InterceptorOptions, type MaybeOptionalOptions, type OmitChainMethodDeep, type OnFinishState, type Segment, type SetOptional, type Value, findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
package/dist/index.mjs ADDED
@@ -0,0 +1,163 @@
1
+ export { group, guard, mapEntries, mapValues, omit, retry, trim } from 'radash';
2
+
3
+ function set(root, segments, value) {
4
+ const ref = { root };
5
+ let currentRef = ref;
6
+ let preSegment = "root";
7
+ for (const segment of segments) {
8
+ currentRef = currentRef[preSegment];
9
+ preSegment = segment;
10
+ }
11
+ currentRef[preSegment] = value;
12
+ return ref.root;
13
+ }
14
+ function get(root, segments) {
15
+ const ref = { root };
16
+ let currentRef = ref;
17
+ let preSegment = "root";
18
+ for (const segment of segments) {
19
+ if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
20
+ return void 0;
21
+ }
22
+ currentRef = currentRef[preSegment];
23
+ preSegment = segment;
24
+ }
25
+ if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
26
+ return void 0;
27
+ }
28
+ return currentRef[preSegment];
29
+ }
30
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
31
+ if (check(payload)) {
32
+ maps.push(segments);
33
+ values.push(payload);
34
+ } else if (Array.isArray(payload)) {
35
+ payload.forEach((v, i) => {
36
+ findDeepMatches(check, v, [...segments, i], maps, values);
37
+ });
38
+ } else if (isObject(payload)) {
39
+ for (const key in payload) {
40
+ findDeepMatches(check, payload[key], [...segments, key], maps, values);
41
+ }
42
+ }
43
+ return { maps, values };
44
+ }
45
+ function isObject(value) {
46
+ if (!value || typeof value !== "object") {
47
+ return false;
48
+ }
49
+ const proto = Object.getPrototypeOf(value);
50
+ return proto === Object.prototype || !proto || !proto.constructor;
51
+ }
52
+ function isTypescriptObject(value) {
53
+ return !!value && (typeof value === "object" || typeof value === "function");
54
+ }
55
+
56
+ function toError(error) {
57
+ if (error instanceof Error) {
58
+ return error;
59
+ }
60
+ if (typeof error === "string") {
61
+ return new Error(error, { cause: error });
62
+ }
63
+ if (isObject(error)) {
64
+ if ("message" in error && typeof error.message === "string") {
65
+ return new Error(error.message, { cause: error });
66
+ }
67
+ if ("name" in error && typeof error.name === "string") {
68
+ return new Error(error.name, { cause: error });
69
+ }
70
+ }
71
+ return new Error("Unknown error", { cause: error });
72
+ }
73
+
74
+ function once(fn) {
75
+ let cached;
76
+ return () => {
77
+ if (cached) {
78
+ return cached.result;
79
+ }
80
+ const result = fn();
81
+ cached = { result };
82
+ return result;
83
+ };
84
+ }
85
+
86
+ function onStart(callback) {
87
+ return async (options, ...rest) => {
88
+ await callback(options, ...rest);
89
+ return await options.next();
90
+ };
91
+ }
92
+ function onSuccess(callback) {
93
+ return async (options, ...rest) => {
94
+ const result = await options.next();
95
+ await callback(result, options, ...rest);
96
+ return result;
97
+ };
98
+ }
99
+ function onError(callback) {
100
+ return async (options, ...rest) => {
101
+ try {
102
+ return await options.next();
103
+ } catch (error) {
104
+ await callback(error, options, ...rest);
105
+ throw error;
106
+ }
107
+ };
108
+ }
109
+ function onFinish(callback) {
110
+ let state;
111
+ return async (options, ...rest) => {
112
+ try {
113
+ const result = await options.next();
114
+ state = [result, void 0, "success"];
115
+ return result;
116
+ } catch (error) {
117
+ state = [void 0, error, "error"];
118
+ throw error;
119
+ } finally {
120
+ await callback(state, options, ...rest);
121
+ }
122
+ };
123
+ }
124
+ async function intercept(interceptors, options, main) {
125
+ let index = 0;
126
+ const next = async (options2) => {
127
+ const interceptor = interceptors[index++];
128
+ if (!interceptor) {
129
+ return await main(options2);
130
+ }
131
+ return await interceptor({
132
+ ...options2,
133
+ next: (newOptions = options2) => next(newOptions)
134
+ });
135
+ };
136
+ return await next(options);
137
+ }
138
+
139
+ function isAsyncIteratorObject(maybe) {
140
+ if (!maybe || typeof maybe !== "object") {
141
+ return false;
142
+ }
143
+ return Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
144
+ }
145
+
146
+ function parseEmptyableJSON(text) {
147
+ if (!text) {
148
+ return void 0;
149
+ }
150
+ return JSON.parse(text);
151
+ }
152
+ function stringifyJSON(value) {
153
+ return JSON.stringify(value);
154
+ }
155
+
156
+ function value(value2, ...args) {
157
+ if (typeof value2 === "function") {
158
+ return value2(...args);
159
+ }
160
+ return value2;
161
+ }
162
+
163
+ export { findDeepMatches, get, intercept, isAsyncIteratorObject, isObject, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, parseEmptyableJSON, set, stringifyJSON, toError, value };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/shared",
3
3
  "type": "module",
4
- "version": "0.0.0-next.e7b4f63",
4
+ "version": "0.0.0-next.e7ee5a9",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,32 +15,20 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
21
- },
22
- "./error": {
23
- "types": "./dist/src/error.d.ts",
24
- "import": "./dist/error.js",
25
- "default": "./dist/error.js"
26
- },
27
- "./🔒/*": {
28
- "types": "./dist/src/*.d.ts"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
29
21
  }
30
22
  },
31
23
  "files": [
32
- "!**/*.map",
33
- "!**/*.tsbuildinfo",
34
24
  "dist"
35
25
  ],
36
26
  "dependencies": {
37
- "@standard-schema/spec": "1.0.0-beta.4",
38
- "is-what": "^5.0.2",
39
27
  "radash": "^12.1.0",
40
28
  "type-fest": "^4.26.1"
41
29
  },
42
30
  "scripts": {
43
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --entry.error=src/error.ts --format=esm --onSuccess='tsc -b --noCheck'",
31
+ "build": "unbuild",
44
32
  "build:watch": "pnpm run build --watch",
45
33
  "type:check": "tsc -b"
46
34
  }
@@ -1,88 +0,0 @@
1
- // src/error.ts
2
- var ORPC_ERROR_CODE_STATUSES = {
3
- BAD_REQUEST: 400,
4
- UNAUTHORIZED: 401,
5
- FORBIDDEN: 403,
6
- NOT_FOUND: 404,
7
- METHOD_NOT_SUPPORTED: 405,
8
- NOT_ACCEPTABLE: 406,
9
- TIMEOUT: 408,
10
- CONFLICT: 409,
11
- PRECONDITION_FAILED: 412,
12
- PAYLOAD_TOO_LARGE: 413,
13
- UNSUPPORTED_MEDIA_TYPE: 415,
14
- UNPROCESSABLE_CONTENT: 422,
15
- TOO_MANY_REQUESTS: 429,
16
- CLIENT_CLOSED_REQUEST: 499,
17
- INTERNAL_SERVER_ERROR: 500,
18
- NOT_IMPLEMENTED: 501,
19
- BAD_GATEWAY: 502,
20
- SERVICE_UNAVAILABLE: 503,
21
- GATEWAY_TIMEOUT: 504
22
- };
23
- var ORPCError = class _ORPCError extends Error {
24
- constructor(zz$oe) {
25
- if (zz$oe.status && (zz$oe.status < 400 || zz$oe.status >= 600)) {
26
- throw new Error("The ORPCError status code must be in the 400-599 range.");
27
- }
28
- super(zz$oe.message, { cause: zz$oe.cause });
29
- this.zz$oe = zz$oe;
30
- }
31
- get code() {
32
- return this.zz$oe.code;
33
- }
34
- get status() {
35
- return this.zz$oe.status ?? ORPC_ERROR_CODE_STATUSES[this.code];
36
- }
37
- get data() {
38
- return this.zz$oe.data;
39
- }
40
- get issues() {
41
- return this.zz$oe.issues;
42
- }
43
- toJSON() {
44
- return {
45
- code: this.code,
46
- status: this.status,
47
- message: this.message,
48
- data: this.data,
49
- issues: this.issues
50
- };
51
- }
52
- static fromJSON(json) {
53
- if (typeof json !== "object" || json === null || !("code" in json) || !Object.keys(ORPC_ERROR_CODE_STATUSES).find((key) => json.code === key) || !("status" in json) || typeof json.status !== "number" || "message" in json && json.message !== void 0 && typeof json.message !== "string" || "issues" in json && json.issues !== void 0 && !Array.isArray(json.issues)) {
54
- return void 0;
55
- }
56
- return new _ORPCError({
57
- code: json.code,
58
- status: json.status,
59
- message: json.message,
60
- data: json.data,
61
- issues: json.issues
62
- });
63
- }
64
- };
65
- function convertToStandardError(error) {
66
- if (error instanceof Error) {
67
- return error;
68
- }
69
- if (typeof error === "string") {
70
- return new Error(error, { cause: error });
71
- }
72
- if (typeof error === "object" && error !== null) {
73
- if ("message" in error && typeof error.message === "string") {
74
- return new Error(error.message, { cause: error });
75
- }
76
- if ("name" in error && typeof error.name === "string") {
77
- return new Error(error.name, { cause: error });
78
- }
79
- }
80
- return new Error("Unknown error", { cause: error });
81
- }
82
-
83
- export {
84
- ORPC_ERROR_CODE_STATUSES,
85
- ORPCError,
86
- convertToStandardError
87
- };
88
- //# sourceMappingURL=chunk-CCTAECMC.js.map
package/dist/error.js DELETED
@@ -1,11 +0,0 @@
1
- import {
2
- ORPCError,
3
- ORPC_ERROR_CODE_STATUSES,
4
- convertToStandardError
5
- } from "./chunk-CCTAECMC.js";
6
- export {
7
- ORPCError,
8
- ORPC_ERROR_CODE_STATUSES,
9
- convertToStandardError
10
- };
11
- //# sourceMappingURL=error.js.map
package/dist/index.js DELETED
@@ -1,180 +0,0 @@
1
- import {
2
- convertToStandardError
3
- } from "./chunk-CCTAECMC.js";
4
-
5
- // src/constants.ts
6
- var ORPC_HANDLER_HEADER = "x-orpc-handler";
7
- var ORPC_HANDLER_VALUE = "orpc";
8
-
9
- // src/hook.ts
10
- async function executeWithHooks(options) {
11
- const interceptors = convertToArray(options.hooks?.interceptor);
12
- const onStarts = convertToArray(options.hooks?.onStart);
13
- const onSuccesses = convertToArray(options.hooks?.onSuccess);
14
- const onErrors = convertToArray(options.hooks?.onError);
15
- const onFinishes = convertToArray(options.hooks?.onFinish);
16
- let currentExecuteIndex = 0;
17
- const next = async () => {
18
- const execute = interceptors[currentExecuteIndex];
19
- if (execute) {
20
- currentExecuteIndex++;
21
- return await execute(options.input, options.context, {
22
- ...options.meta,
23
- next
24
- });
25
- }
26
- let state = { status: "pending", input: options.input, output: void 0, error: void 0 };
27
- try {
28
- for (const onStart of onStarts) {
29
- await onStart(state, options.context, options.meta);
30
- }
31
- const output = await options.execute();
32
- state = { status: "success", input: options.input, output, error: void 0 };
33
- for (let i = onSuccesses.length - 1; i >= 0; i--) {
34
- await onSuccesses[i](state, options.context, options.meta);
35
- }
36
- } catch (e) {
37
- state = { status: "error", input: options.input, error: convertToStandardError(e), output: void 0 };
38
- for (let i = onErrors.length - 1; i >= 0; i--) {
39
- try {
40
- await onErrors[i](state, options.context, options.meta);
41
- } catch (e2) {
42
- state = { status: "error", input: options.input, error: convertToStandardError(e2), output: void 0 };
43
- }
44
- }
45
- }
46
- for (let i = onFinishes.length - 1; i >= 0; i--) {
47
- try {
48
- await onFinishes[i](state, options.context, options.meta);
49
- } catch (e) {
50
- state = { status: "error", input: options.input, error: convertToStandardError(e), output: void 0 };
51
- }
52
- }
53
- if (state.status === "error") {
54
- throw state.error;
55
- }
56
- return state.output;
57
- };
58
- return await next();
59
- }
60
- function convertToArray(value2) {
61
- if (value2 === void 0) {
62
- return [];
63
- }
64
- return Array.isArray(value2) ? value2 : [value2];
65
- }
66
-
67
- // src/json.ts
68
- function parseJSONSafely(text) {
69
- if (text === "")
70
- return void 0;
71
- try {
72
- return JSON.parse(text);
73
- } catch {
74
- return text;
75
- }
76
- }
77
-
78
- // src/object.ts
79
- import { isPlainObject } from "is-what";
80
- function set(root, segments, value2) {
81
- const ref = { root };
82
- let currentRef = ref;
83
- let preSegment = "root";
84
- for (const segment of segments) {
85
- currentRef = currentRef[preSegment];
86
- preSegment = segment;
87
- }
88
- currentRef[preSegment] = value2;
89
- return ref.root;
90
- }
91
- function get(root, segments) {
92
- const ref = { root };
93
- let currentRef = ref;
94
- let preSegment = "root";
95
- for (const segment of segments) {
96
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
97
- return void 0;
98
- }
99
- currentRef = currentRef[preSegment];
100
- preSegment = segment;
101
- }
102
- if (typeof currentRef !== "object" && typeof currentRef !== "function" || currentRef === null) {
103
- return void 0;
104
- }
105
- return currentRef[preSegment];
106
- }
107
- function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
108
- if (check(payload)) {
109
- maps.push(segments);
110
- values.push(payload);
111
- } else if (Array.isArray(payload)) {
112
- payload.forEach((v, i) => {
113
- findDeepMatches(check, v, [...segments, i], maps, values);
114
- });
115
- } else if (isPlainObject(payload)) {
116
- for (const key in payload) {
117
- findDeepMatches(check, payload[key], [...segments, key], maps, values);
118
- }
119
- }
120
- return { maps, values };
121
- }
122
-
123
- // src/proxy.ts
124
- function createCallableObject(obj, handler) {
125
- const proxy = new Proxy(handler, {
126
- has(target, key) {
127
- return Reflect.has(obj, key) || Reflect.has(target, key);
128
- },
129
- ownKeys(target) {
130
- return Array.from(new Set(Reflect.ownKeys(obj).concat(...Reflect.ownKeys(target))));
131
- },
132
- get(target, key) {
133
- if (!Reflect.has(target, key) || Reflect.has(obj, key)) {
134
- return Reflect.get(obj, key);
135
- }
136
- return Reflect.get(target, key);
137
- },
138
- defineProperty(_, key, descriptor) {
139
- return Reflect.defineProperty(obj, key, descriptor);
140
- },
141
- set(_, key, value2) {
142
- return Reflect.set(obj, key, value2);
143
- },
144
- deleteProperty(target, key) {
145
- return Reflect.deleteProperty(target, key) && Reflect.deleteProperty(obj, key);
146
- }
147
- });
148
- return proxy;
149
- }
150
-
151
- // src/value.ts
152
- function value(value2) {
153
- if (typeof value2 === "function") {
154
- return value2();
155
- }
156
- return value2;
157
- }
158
-
159
- // src/index.ts
160
- import { isPlainObject as isPlainObject2 } from "is-what";
161
- import { guard, mapEntries, mapValues, omit, trim } from "radash";
162
- export {
163
- ORPC_HANDLER_HEADER,
164
- ORPC_HANDLER_VALUE,
165
- convertToArray,
166
- createCallableObject,
167
- executeWithHooks,
168
- findDeepMatches,
169
- get,
170
- guard,
171
- isPlainObject2 as isPlainObject,
172
- mapEntries,
173
- mapValues,
174
- omit,
175
- parseJSONSafely,
176
- set,
177
- trim,
178
- value
179
- };
180
- //# sourceMappingURL=index.js.map
@@ -1,3 +0,0 @@
1
- export declare const ORPC_HANDLER_HEADER = "x-orpc-handler";
2
- export declare const ORPC_HANDLER_VALUE = "orpc";
3
- //# sourceMappingURL=constants.d.ts.map
@@ -1,65 +0,0 @@
1
- import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- export declare const ORPC_ERROR_CODE_STATUSES: {
3
- readonly BAD_REQUEST: 400;
4
- readonly UNAUTHORIZED: 401;
5
- readonly FORBIDDEN: 403;
6
- readonly NOT_FOUND: 404;
7
- readonly METHOD_NOT_SUPPORTED: 405;
8
- readonly NOT_ACCEPTABLE: 406;
9
- readonly TIMEOUT: 408;
10
- readonly CONFLICT: 409;
11
- readonly PRECONDITION_FAILED: 412;
12
- readonly PAYLOAD_TOO_LARGE: 413;
13
- readonly UNSUPPORTED_MEDIA_TYPE: 415;
14
- readonly UNPROCESSABLE_CONTENT: 422;
15
- readonly TOO_MANY_REQUESTS: 429;
16
- readonly CLIENT_CLOSED_REQUEST: 499;
17
- readonly INTERNAL_SERVER_ERROR: 500;
18
- readonly NOT_IMPLEMENTED: 501;
19
- readonly BAD_GATEWAY: 502;
20
- readonly SERVICE_UNAVAILABLE: 503;
21
- readonly GATEWAY_TIMEOUT: 504;
22
- };
23
- export type ORPCErrorCode = keyof typeof ORPC_ERROR_CODE_STATUSES;
24
- export interface ORPCErrorJSON<TCode extends ORPCErrorCode, TData> {
25
- code: TCode;
26
- status: number;
27
- message: string;
28
- data: TData;
29
- issues?: readonly StandardSchemaV1.Issue[];
30
- }
31
- export type ANY_ORPC_ERROR_JSON = ORPCErrorJSON<any, any>;
32
- export type WELL_ORPC_ERROR_JSON = ORPCErrorJSON<ORPCErrorCode, unknown>;
33
- export declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
34
- zz$oe: {
35
- code: TCode;
36
- status?: number;
37
- message?: string;
38
- cause?: unknown;
39
- issues?: readonly StandardSchemaV1.Issue[];
40
- } & (undefined extends TData ? {
41
- data?: TData;
42
- } : {
43
- data: TData;
44
- });
45
- constructor(zz$oe: {
46
- code: TCode;
47
- status?: number;
48
- message?: string;
49
- cause?: unknown;
50
- issues?: readonly StandardSchemaV1.Issue[];
51
- } & (undefined extends TData ? {
52
- data?: TData;
53
- } : {
54
- data: TData;
55
- }));
56
- get code(): TCode;
57
- get status(): number;
58
- get data(): TData;
59
- get issues(): readonly StandardSchemaV1.Issue[] | undefined;
60
- toJSON(): ORPCErrorJSON<TCode, TData>;
61
- static fromJSON(json: unknown): ORPCError<ORPCErrorCode, any> | undefined;
62
- }
63
- export type WELL_ORPC_ERROR = ORPCError<ORPCErrorCode, unknown>;
64
- export declare function convertToStandardError(error: unknown): Error;
65
- //# sourceMappingURL=error.d.ts.map
@@ -1,2 +0,0 @@
1
- export type AnyFunction = (...args: any[]) => any;
2
- //# sourceMappingURL=function.d.ts.map
@@ -1,42 +0,0 @@
1
- import type { Arrayable, Promisable } from 'type-fest';
2
- export type OnStartState<TInput> = {
3
- status: 'pending';
4
- input: TInput;
5
- output: undefined;
6
- error: undefined;
7
- };
8
- export type OnSuccessState<TInput, TOutput> = {
9
- status: 'success';
10
- input: TInput;
11
- output: TOutput;
12
- error: undefined;
13
- };
14
- export type OnErrorState<TInput> = {
15
- status: 'error';
16
- input: TInput;
17
- output: undefined;
18
- error: Error;
19
- };
20
- export interface BaseHookMeta<TOutput> {
21
- next: () => Promise<TOutput>;
22
- }
23
- export interface Hooks<TInput, TOutput, TContext, TMeta extends (Record<string, any> & {
24
- next?: never;
25
- }) | undefined> {
26
- interceptor?: Arrayable<(input: TInput, context: TContext, meta: (TMeta extends undefined ? unknown : TMeta) & BaseHookMeta<TOutput>) => Promise<TOutput>>;
27
- onStart?: Arrayable<(state: OnStartState<TInput>, context: TContext, meta: TMeta) => Promisable<void>>;
28
- onSuccess?: Arrayable<(state: OnSuccessState<TInput, TOutput>, context: TContext, meta: TMeta) => Promisable<void>>;
29
- onError?: Arrayable<(state: OnErrorState<TInput>, context: TContext, meta: TMeta) => Promisable<void>>;
30
- onFinish?: Arrayable<(state: OnSuccessState<TInput, TOutput> | OnErrorState<TInput>, context: TContext, meta: TMeta) => Promisable<void>>;
31
- }
32
- export declare function executeWithHooks<TInput, TOutput, TContext, TMeta extends (Record<string, any> & {
33
- next?: never;
34
- }) | undefined>(options: {
35
- hooks?: Hooks<TInput, TOutput, TContext, TMeta>;
36
- input: TInput;
37
- context: TContext;
38
- meta: TMeta;
39
- execute: BaseHookMeta<TOutput>['next'];
40
- }): Promise<TOutput>;
41
- export declare function convertToArray<T>(value: undefined | T | readonly T[]): readonly T[];
42
- //# sourceMappingURL=hook.d.ts.map
@@ -1,11 +0,0 @@
1
- export * from './constants';
2
- export * from './function';
3
- export * from './hook';
4
- export * from './json';
5
- export * from './object';
6
- export * from './proxy';
7
- export * from './value';
8
- export { isPlainObject } from 'is-what';
9
- export { guard, mapEntries, mapValues, omit, trim } from 'radash';
10
- export type * from 'type-fest';
11
- //# sourceMappingURL=index.d.ts.map
@@ -1,2 +0,0 @@
1
- export declare function parseJSONSafely(text: string): unknown;
2
- //# sourceMappingURL=json.d.ts.map
@@ -1,8 +0,0 @@
1
- export type Segment = string | number;
2
- export declare function set(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>, value: unknown): unknown;
3
- export declare function get(root: Readonly<Record<string, unknown> | unknown[]>, segments: Readonly<Segment[]>): unknown;
4
- export declare function findDeepMatches(check: (value: unknown) => boolean, payload: unknown, segments?: Segment[], maps?: Segment[][], values?: unknown[]): {
5
- maps: Segment[][];
6
- values: unknown[];
7
- };
8
- //# sourceMappingURL=object.d.ts.map
@@ -1,3 +0,0 @@
1
- import type { AnyFunction } from './function';
2
- export declare function createCallableObject<TObject extends object, THandler extends AnyFunction>(obj: TObject, handler: THandler): TObject & THandler;
3
- //# sourceMappingURL=proxy.d.ts.map
@@ -1,4 +0,0 @@
1
- import type { Promisable } from 'type-fest';
2
- export type Value<T> = T | (() => Promisable<T>);
3
- export declare function value<T extends Value<any>>(value: T): Promise<T extends Value<infer U> ? U : never>;
4
- //# sourceMappingURL=value.d.ts.map