@orpc/contract 0.0.0-next.a2e4a58 → 0.0.0-next.a4ecb29

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/dist/index.js DELETED
@@ -1,503 +0,0 @@
1
- // src/procedure.ts
2
- var ContractProcedure = class {
3
- "~type" = "ContractProcedure";
4
- "~orpc";
5
- constructor(def) {
6
- if (def.route?.successStatus && (def.route.successStatus < 200 || def.route?.successStatus > 299)) {
7
- throw new Error("[ContractProcedure] The successStatus must be between 200 and 299");
8
- }
9
- if (Object.values(def.errorMap ?? {}).some((val) => val && val.status && (val.status < 400 || val.status > 599))) {
10
- throw new Error("[ContractProcedure] The error status code must be in the 400-599 range.");
11
- }
12
- this["~orpc"] = def;
13
- }
14
- };
15
- function isContractProcedure(item) {
16
- if (item instanceof ContractProcedure) {
17
- return true;
18
- }
19
- return (typeof item === "object" || typeof item === "function") && item !== null && "~type" in item && item["~type"] === "ContractProcedure" && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "InputSchema" in item["~orpc"] && "OutputSchema" in item["~orpc"] && "errorMap" in item["~orpc"];
20
- }
21
-
22
- // src/procedure-decorated.ts
23
- var DecoratedContractProcedure = class _DecoratedContractProcedure extends ContractProcedure {
24
- static decorate(procedure) {
25
- if (procedure instanceof _DecoratedContractProcedure) {
26
- return procedure;
27
- }
28
- return new _DecoratedContractProcedure(procedure["~orpc"]);
29
- }
30
- errors(errors) {
31
- return new _DecoratedContractProcedure({
32
- ...this["~orpc"],
33
- errorMap: {
34
- ...this["~orpc"].errorMap,
35
- ...errors
36
- }
37
- });
38
- }
39
- route(route) {
40
- return new _DecoratedContractProcedure({
41
- ...this["~orpc"],
42
- route: {
43
- ...this["~orpc"].route,
44
- ...route
45
- }
46
- });
47
- }
48
- prefix(prefix) {
49
- return new _DecoratedContractProcedure({
50
- ...this["~orpc"],
51
- ...this["~orpc"].route?.path ? {
52
- route: {
53
- ...this["~orpc"].route,
54
- path: `${prefix}${this["~orpc"].route.path}`
55
- }
56
- } : void 0
57
- });
58
- }
59
- unshiftTag(...tags) {
60
- return new _DecoratedContractProcedure({
61
- ...this["~orpc"],
62
- route: {
63
- ...this["~orpc"].route,
64
- tags: [
65
- ...tags,
66
- ...this["~orpc"].route?.tags?.filter((tag) => !tags.includes(tag)) ?? []
67
- ]
68
- }
69
- });
70
- }
71
- };
72
-
73
- // src/procedure-builder-with-input.ts
74
- var ContractProcedureBuilderWithInput = class _ContractProcedureBuilderWithInput extends ContractProcedure {
75
- errors(errors) {
76
- const decorated = DecoratedContractProcedure.decorate(this).errors(errors);
77
- return new _ContractProcedureBuilderWithInput(decorated["~orpc"]);
78
- }
79
- route(route) {
80
- const decorated = DecoratedContractProcedure.decorate(this).route(route);
81
- return new _ContractProcedureBuilderWithInput(decorated["~orpc"]);
82
- }
83
- prefix(prefix) {
84
- const decorated = DecoratedContractProcedure.decorate(this).prefix(prefix);
85
- return new _ContractProcedureBuilderWithInput(decorated["~orpc"]);
86
- }
87
- unshiftTag(...tags) {
88
- const decorated = DecoratedContractProcedure.decorate(this).unshiftTag(...tags);
89
- return new _ContractProcedureBuilderWithInput(decorated["~orpc"]);
90
- }
91
- output(schema, example) {
92
- return new DecoratedContractProcedure({
93
- ...this["~orpc"],
94
- OutputSchema: schema,
95
- outputExample: example
96
- });
97
- }
98
- };
99
-
100
- // src/procedure-builder-with-output.ts
101
- var ContractProcedureBuilderWithOutput = class _ContractProcedureBuilderWithOutput extends ContractProcedure {
102
- errors(errors) {
103
- const decorated = DecoratedContractProcedure.decorate(this).errors(errors);
104
- return new _ContractProcedureBuilderWithOutput(decorated["~orpc"]);
105
- }
106
- route(route) {
107
- const decorated = DecoratedContractProcedure.decorate(this).route(route);
108
- return new _ContractProcedureBuilderWithOutput(decorated["~orpc"]);
109
- }
110
- prefix(prefix) {
111
- const decorated = DecoratedContractProcedure.decorate(this).prefix(prefix);
112
- return new _ContractProcedureBuilderWithOutput(decorated["~orpc"]);
113
- }
114
- unshiftTag(...tags) {
115
- const decorated = DecoratedContractProcedure.decorate(this).unshiftTag(...tags);
116
- return new _ContractProcedureBuilderWithOutput(decorated["~orpc"]);
117
- }
118
- input(schema, example) {
119
- return new DecoratedContractProcedure({
120
- ...this["~orpc"],
121
- InputSchema: schema,
122
- inputExample: example
123
- });
124
- }
125
- };
126
-
127
- // src/procedure-builder.ts
128
- var ContractProcedureBuilder = class _ContractProcedureBuilder extends ContractProcedure {
129
- errors(errors) {
130
- const decorated = DecoratedContractProcedure.decorate(this).errors(errors);
131
- return new _ContractProcedureBuilder(decorated["~orpc"]);
132
- }
133
- route(route) {
134
- const decorated = DecoratedContractProcedure.decorate(this).route(route);
135
- return new _ContractProcedureBuilder(decorated["~orpc"]);
136
- }
137
- prefix(prefix) {
138
- const decorated = DecoratedContractProcedure.decorate(this).prefix(prefix);
139
- return new _ContractProcedureBuilder(decorated["~orpc"]);
140
- }
141
- unshiftTag(...tags) {
142
- const decorated = DecoratedContractProcedure.decorate(this).unshiftTag(...tags);
143
- return new _ContractProcedureBuilder(decorated["~orpc"]);
144
- }
145
- input(schema, example) {
146
- return new ContractProcedureBuilderWithInput({
147
- ...this["~orpc"],
148
- InputSchema: schema,
149
- inputExample: example
150
- });
151
- }
152
- output(schema, example) {
153
- return new ContractProcedureBuilderWithOutput({
154
- ...this["~orpc"],
155
- OutputSchema: schema,
156
- outputExample: example
157
- });
158
- }
159
- };
160
-
161
- // src/router-builder.ts
162
- var ContractRouterBuilder = class _ContractRouterBuilder {
163
- "~type" = "ContractProcedure";
164
- "~orpc";
165
- constructor(def) {
166
- this["~orpc"] = def;
167
- }
168
- prefix(prefix) {
169
- return new _ContractRouterBuilder({
170
- ...this["~orpc"],
171
- prefix: `${this["~orpc"].prefix ?? ""}${prefix}`
172
- });
173
- }
174
- tag(...tags) {
175
- return new _ContractRouterBuilder({
176
- ...this["~orpc"],
177
- tags: [...this["~orpc"].tags ?? [], ...tags]
178
- });
179
- }
180
- errors(errors) {
181
- return new _ContractRouterBuilder({
182
- ...this["~orpc"],
183
- errorMap: {
184
- ...this["~orpc"].errorMap,
185
- ...errors
186
- }
187
- });
188
- }
189
- router(router) {
190
- if (isContractProcedure(router)) {
191
- let decorated = DecoratedContractProcedure.decorate(router);
192
- if (this["~orpc"].tags) {
193
- decorated = decorated.unshiftTag(...this["~orpc"].tags);
194
- }
195
- if (this["~orpc"].prefix) {
196
- decorated = decorated.prefix(this["~orpc"].prefix);
197
- }
198
- decorated = decorated.errors(this["~orpc"].errorMap);
199
- return decorated;
200
- }
201
- const adapted = {};
202
- for (const key in router) {
203
- adapted[key] = this.router(router[key]);
204
- }
205
- return adapted;
206
- }
207
- };
208
-
209
- // src/builder.ts
210
- var ContractBuilder = class _ContractBuilder extends ContractProcedure {
211
- constructor(def) {
212
- super(def);
213
- }
214
- config(config) {
215
- return new _ContractBuilder({
216
- ...this["~orpc"],
217
- config: {
218
- ...this["~orpc"].config,
219
- ...config
220
- }
221
- });
222
- }
223
- errors(errors) {
224
- return new _ContractBuilder({
225
- ...this["~orpc"],
226
- errorMap: {
227
- ...this["~orpc"].errorMap,
228
- ...errors
229
- }
230
- });
231
- }
232
- route(route) {
233
- return new ContractProcedureBuilder({
234
- route: {
235
- ...this["~orpc"].config.initialRoute,
236
- ...route
237
- },
238
- InputSchema: void 0,
239
- OutputSchema: void 0,
240
- errorMap: this["~orpc"].errorMap
241
- });
242
- }
243
- input(schema, example) {
244
- return new ContractProcedureBuilderWithInput({
245
- route: this["~orpc"].config.initialRoute,
246
- InputSchema: schema,
247
- inputExample: example,
248
- OutputSchema: void 0,
249
- errorMap: this["~orpc"].errorMap
250
- });
251
- }
252
- output(schema, example) {
253
- return new ContractProcedureBuilderWithOutput({
254
- route: this["~orpc"].config.initialRoute,
255
- OutputSchema: schema,
256
- outputExample: example,
257
- InputSchema: void 0,
258
- errorMap: this["~orpc"].errorMap
259
- });
260
- }
261
- prefix(prefix) {
262
- return new ContractRouterBuilder({
263
- prefix,
264
- errorMap: this["~orpc"].errorMap
265
- });
266
- }
267
- tag(...tags) {
268
- return new ContractRouterBuilder({
269
- tags,
270
- errorMap: this["~orpc"].errorMap
271
- });
272
- }
273
- router(router) {
274
- return new ContractRouterBuilder({
275
- errorMap: this["~orpc"].errorMap
276
- }).router(router);
277
- }
278
- };
279
-
280
- // src/error-orpc.ts
281
- import { isPlainObject } from "@orpc/shared";
282
- var COMMON_ORPC_ERROR_DEFS = {
283
- BAD_REQUEST: {
284
- status: 400,
285
- message: "Bad Request"
286
- },
287
- UNAUTHORIZED: {
288
- status: 401,
289
- message: "Unauthorized"
290
- },
291
- FORBIDDEN: {
292
- status: 403,
293
- message: "Forbidden"
294
- },
295
- NOT_FOUND: {
296
- status: 404,
297
- message: "Not Found"
298
- },
299
- METHOD_NOT_SUPPORTED: {
300
- status: 405,
301
- message: "Method Not Supported"
302
- },
303
- NOT_ACCEPTABLE: {
304
- status: 406,
305
- message: "Not Acceptable"
306
- },
307
- TIMEOUT: {
308
- status: 408,
309
- message: "Request Timeout"
310
- },
311
- CONFLICT: {
312
- status: 409,
313
- message: "Conflict"
314
- },
315
- PRECONDITION_FAILED: {
316
- status: 412,
317
- message: "Precondition Failed"
318
- },
319
- PAYLOAD_TOO_LARGE: {
320
- status: 413,
321
- message: "Payload Too Large"
322
- },
323
- UNSUPPORTED_MEDIA_TYPE: {
324
- status: 415,
325
- message: "Unsupported Media Type"
326
- },
327
- UNPROCESSABLE_CONTENT: {
328
- status: 422,
329
- message: "Unprocessable Content"
330
- },
331
- TOO_MANY_REQUESTS: {
332
- status: 429,
333
- message: "Too Many Requests"
334
- },
335
- CLIENT_CLOSED_REQUEST: {
336
- status: 499,
337
- message: "Client Closed Request"
338
- },
339
- INTERNAL_SERVER_ERROR: {
340
- status: 500,
341
- message: "Internal Server Error"
342
- },
343
- NOT_IMPLEMENTED: {
344
- status: 501,
345
- message: "Not Implemented"
346
- },
347
- BAD_GATEWAY: {
348
- status: 502,
349
- message: "Bad Gateway"
350
- },
351
- SERVICE_UNAVAILABLE: {
352
- status: 503,
353
- message: "Service Unavailable"
354
- },
355
- GATEWAY_TIMEOUT: {
356
- status: 504,
357
- message: "Gateway Timeout"
358
- }
359
- };
360
- function fallbackORPCErrorStatus(code, status) {
361
- return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
362
- }
363
- function fallbackORPCErrorMessage(code, message) {
364
- return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
365
- }
366
- var ORPCError = class extends Error {
367
- defined;
368
- code;
369
- status;
370
- data;
371
- constructor(options) {
372
- if (options.status && (options.status < 400 || options.status >= 600)) {
373
- throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
374
- }
375
- const message = fallbackORPCErrorMessage(options.code, options.message);
376
- super(message, options);
377
- this.code = options.code;
378
- this.status = fallbackORPCErrorStatus(options.code, options.status);
379
- this.defined = options.defined ?? false;
380
- this.data = options.data;
381
- }
382
- toJSON() {
383
- return {
384
- defined: this.defined,
385
- code: this.code,
386
- status: this.status,
387
- message: this.message,
388
- data: this.data
389
- };
390
- }
391
- static isValidJSON(json) {
392
- return isPlainObject(json) && "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && "message" in json && typeof json.message === "string";
393
- }
394
- };
395
- function isDefinedError(error) {
396
- return error instanceof ORPCError && error.defined;
397
- }
398
- async function validateORPCError(map, error) {
399
- const { code, status, message, data, cause, defined } = error;
400
- const config = map?.[error.code];
401
- if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
402
- return defined ? new ORPCError({ defined: false, code, status, message, data, cause }) : error;
403
- }
404
- if (!config.data) {
405
- return defined ? error : new ORPCError({ defined: true, code, status, message, data, cause });
406
- }
407
- const validated = await config.data["~standard"].validate(error.data);
408
- if (validated.issues) {
409
- return defined ? new ORPCError({ defined: false, code, status, message, data, cause }) : error;
410
- }
411
- return new ORPCError({
412
- defined: true,
413
- code,
414
- status,
415
- message,
416
- data: validated.value,
417
- cause
418
- });
419
- }
420
-
421
- // src/client-utils.ts
422
- async function safe(promise) {
423
- try {
424
- const output = await promise;
425
- return [output, void 0, false];
426
- } catch (e) {
427
- const error = e;
428
- if (isDefinedError(error)) {
429
- return [void 0, error, true];
430
- }
431
- return [void 0, error, false];
432
- }
433
- }
434
-
435
- // src/config.ts
436
- var DEFAULT_CONFIG = {
437
- defaultMethod: "POST",
438
- defaultSuccessStatus: 200,
439
- defaultSuccessDescription: "OK",
440
- defaultInputStructure: "compact",
441
- defaultOutputStructure: "compact"
442
- };
443
- function fallbackContractConfig(key, value) {
444
- if (value === void 0) {
445
- return DEFAULT_CONFIG[key];
446
- }
447
- return value;
448
- }
449
-
450
- // src/error.ts
451
- var ValidationError = class extends Error {
452
- issues;
453
- constructor(options) {
454
- super(options.message, options);
455
- this.issues = options.issues;
456
- }
457
- };
458
-
459
- // src/schema-utils.ts
460
- function type(...[map]) {
461
- return {
462
- "~standard": {
463
- vendor: "custom",
464
- version: 1,
465
- async validate(value) {
466
- if (map) {
467
- return { value: await map(value) };
468
- }
469
- return { value };
470
- }
471
- }
472
- };
473
- }
474
-
475
- // src/index.ts
476
- var oc = new ContractBuilder({
477
- errorMap: {},
478
- InputSchema: void 0,
479
- OutputSchema: void 0,
480
- config: {}
481
- });
482
- export {
483
- COMMON_ORPC_ERROR_DEFS,
484
- ContractBuilder,
485
- ContractProcedure,
486
- ContractProcedureBuilder,
487
- ContractProcedureBuilderWithInput,
488
- ContractProcedureBuilderWithOutput,
489
- ContractRouterBuilder,
490
- DecoratedContractProcedure,
491
- ORPCError,
492
- ValidationError,
493
- fallbackContractConfig,
494
- fallbackORPCErrorMessage,
495
- fallbackORPCErrorStatus,
496
- isContractProcedure,
497
- isDefinedError,
498
- oc,
499
- safe,
500
- type,
501
- validateORPCError
502
- };
503
- //# sourceMappingURL=index.js.map
@@ -1,29 +0,0 @@
1
- import type { ErrorMap, ErrorMapGuard, ErrorMapSuggestions, StrictErrorMap } from './error-map';
2
- import type { ContractProcedureDef, RouteOptions } from './procedure';
3
- import type { ContractRouter } from './router';
4
- import type { AdaptedContractRouter } from './router-builder';
5
- import type { HTTPPath, Schema, SchemaInput, SchemaOutput } from './types';
6
- import { ContractProcedure } from './procedure';
7
- import { ContractProcedureBuilder } from './procedure-builder';
8
- import { ContractProcedureBuilderWithInput } from './procedure-builder-with-input';
9
- import { ContractProcedureBuilderWithOutput } from './procedure-builder-with-output';
10
- import { ContractRouterBuilder } from './router-builder';
11
- export interface ContractBuilderConfig {
12
- initialRoute?: RouteOptions;
13
- }
14
- export interface ContractBuilderDef<TErrorMap extends ErrorMap> extends ContractProcedureDef<undefined, undefined, TErrorMap> {
15
- config: ContractBuilderConfig;
16
- }
17
- export declare class ContractBuilder<TErrorMap extends ErrorMap> extends ContractProcedure<undefined, undefined, TErrorMap> {
18
- '~orpc': ContractBuilderDef<TErrorMap>;
19
- constructor(def: ContractBuilderDef<TErrorMap>);
20
- config(config: ContractBuilderConfig): ContractBuilder<TErrorMap>;
21
- errors<const U extends ErrorMap & ErrorMapGuard<TErrorMap> & ErrorMapSuggestions>(errors: U): ContractBuilder<U & TErrorMap>;
22
- route(route: RouteOptions): ContractProcedureBuilder<TErrorMap>;
23
- input<U extends Schema>(schema: U, example?: SchemaInput<U>): ContractProcedureBuilderWithInput<U, TErrorMap>;
24
- output<U extends Schema>(schema: U, example?: SchemaOutput<U>): ContractProcedureBuilderWithOutput<U, TErrorMap>;
25
- prefix(prefix: HTTPPath): ContractRouterBuilder<TErrorMap>;
26
- tag(...tags: string[]): ContractRouterBuilder<TErrorMap>;
27
- router<T extends ContractRouter<ErrorMap & Partial<StrictErrorMap<TErrorMap>>>>(router: T): AdaptedContractRouter<T, TErrorMap>;
28
- }
29
- //# sourceMappingURL=builder.d.ts.map
@@ -1,5 +0,0 @@
1
- import type { ClientPromiseResult } from './client';
2
- import { type ORPCError } from './error-orpc';
3
- export type SafeResult<TOutput, TError extends Error> = [output: TOutput, error: undefined, isDefinedError: false] | [output: undefined, error: TError, isDefinedError: false] | [output: undefined, error: Extract<TError, ORPCError<any, any>>, isDefinedError: true];
4
- export declare function safe<TOutput, TError extends Error>(promise: ClientPromiseResult<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
5
- //# sourceMappingURL=client-utils.d.ts.map
@@ -1,19 +0,0 @@
1
- import type { AbortSignal } from './types';
2
- export type ClientOptions<TClientContext> = {
3
- signal?: AbortSignal;
4
- } & (undefined extends TClientContext ? {
5
- context?: TClientContext;
6
- } : {
7
- context: TClientContext;
8
- });
9
- export type ClientRest<TClientContext, TInput> = [input: TInput, options: ClientOptions<TClientContext>] | (undefined extends TInput & TClientContext ? [] : never) | (undefined extends TClientContext ? [input: TInput] : never);
10
- export type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
11
- __typeError?: TError;
12
- };
13
- export interface Client<TClientContext, TInput, TOutput, TError extends Error> {
14
- (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
15
- }
16
- export type NestedClient<TClientContext> = Client<TClientContext, any, any, any> | {
17
- [k: string]: NestedClient<TClientContext>;
18
- };
19
- //# sourceMappingURL=client.d.ts.map
@@ -1,10 +0,0 @@
1
- import type { HTTPMethod, InputStructure } from './types';
2
- export interface ContractConfig {
3
- defaultMethod: HTTPMethod;
4
- defaultSuccessStatus: number;
5
- defaultSuccessDescription: string;
6
- defaultInputStructure: InputStructure;
7
- defaultOutputStructure: InputStructure;
8
- }
9
- export declare function fallbackContractConfig<T extends keyof ContractConfig>(key: T, value: ContractConfig[T] | undefined): ContractConfig[T];
10
- //# sourceMappingURL=config.d.ts.map
@@ -1,58 +0,0 @@
1
- import type { CommonORPCErrorCode } from './error-orpc';
2
- import type { Schema } from './types';
3
- export type ErrorMapItem<TDataSchema extends Schema> = {
4
- /**
5
- *
6
- * @default 500
7
- */
8
- status?: number;
9
- message?: string;
10
- description?: string;
11
- data?: TDataSchema;
12
- };
13
- export interface ErrorMap {
14
- [k: string]: ErrorMapItem<Schema>;
15
- }
16
- /**
17
- * const U extends ErrorMap & ErrorMapGuard<TErrorMap> & ErrorMapSuggestions
18
- *
19
- * Purpose:
20
- * - Helps `U` suggest `CommonORPCErrorCode` to the user when typing.
21
- *
22
- * Why not replace `ErrorMap` with `ErrorMapSuggestions`?
23
- * - `ErrorMapSuggestions` has a drawback: it allows `undefined` values for items.
24
- * - `ErrorMapGuard<TErrorMap>` uses `Partial`, which can introduce `undefined` values.
25
- *
26
- * This could lead to unintended behavior where `undefined` values override `TErrorMap`,
27
- * potentially resulting in a `never` type after merging.
28
- *
29
- * Recommendation:
30
- * - Use `ErrorMapSuggestions` to assist users in typing correctly but do not replace `ErrorMap`.
31
- * - Ensure `ErrorMapGuard<TErrorMap>` is adjusted to prevent `undefined` values.
32
- */
33
- export type ErrorMapSuggestions = {
34
- [key in CommonORPCErrorCode | (string & {})]?: ErrorMapItem<Schema>;
35
- };
36
- /**
37
- * `U` extends `ErrorMap` & `ErrorMapGuard<TErrorMap>`
38
- *
39
- * `ErrorMapGuard` is a utility type that ensures `U` cannot redefine the structure of `TErrorMap`.
40
- * It achieves this by setting each key in `TErrorMap` to `never`, effectively preventing any redefinition.
41
- *
42
- * Why not just use `Partial<TErrorMap>`?
43
- * - Allowing users to redefine existing error map items would require using `StrictErrorMap`.
44
- * - However, I prefer not to use `StrictErrorMap` frequently, due to perceived performance concerns,
45
- * though this has not been benchmarked and is based on personal preference.
46
- *
47
- */
48
- export type ErrorMapGuard<TErrorMap extends ErrorMap> = {
49
- [K in keyof TErrorMap]?: never;
50
- };
51
- /**
52
- * Since `undefined` has a specific meaning (it use default value),
53
- * we ensure all additional properties in each item of the ErrorMap are explicitly set to `undefined`.
54
- */
55
- export type StrictErrorMap<T extends ErrorMap> = {
56
- [K in keyof T]: T[K] & Partial<Record<Exclude<keyof ErrorMapItem<any>, keyof T[K]>, undefined>>;
57
- };
58
- //# sourceMappingURL=error-map.d.ts.map