@orpc/contract 0.0.0-next.fe39bf3 → 0.0.0-next.fe5c63f

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.mjs ADDED
@@ -0,0 +1,355 @@
1
+ import { isORPCErrorStatus, mapEventIterator, ORPCError } from '@orpc/client';
2
+ export { ORPCError } from '@orpc/client';
3
+ import { isAsyncIteratorObject, get, isTypescriptObject, isPropertyKey } from '@orpc/shared';
4
+
5
+ class ValidationError extends Error {
6
+ issues;
7
+ constructor(options) {
8
+ super(options.message, options);
9
+ this.issues = options.issues;
10
+ }
11
+ }
12
+ function mergeErrorMap(errorMap1, errorMap2) {
13
+ return { ...errorMap1, ...errorMap2 };
14
+ }
15
+
16
+ function mergeMeta(meta1, meta2) {
17
+ return { ...meta1, ...meta2 };
18
+ }
19
+
20
+ class ContractProcedure {
21
+ /**
22
+ * This property holds the defined options for the contract procedure.
23
+ */
24
+ "~orpc";
25
+ constructor(def) {
26
+ if (def.route?.successStatus && isORPCErrorStatus(def.route.successStatus)) {
27
+ throw new Error("[ContractProcedure] Invalid successStatus.");
28
+ }
29
+ if (Object.values(def.errorMap).some((val) => val && val.status && !isORPCErrorStatus(val.status))) {
30
+ throw new Error("[ContractProcedure] Invalid error status code.");
31
+ }
32
+ this["~orpc"] = def;
33
+ }
34
+ }
35
+ function isContractProcedure(item) {
36
+ if (item instanceof ContractProcedure) {
37
+ return true;
38
+ }
39
+ return (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
40
+ }
41
+
42
+ function mergeRoute(a, b) {
43
+ return { ...a, ...b };
44
+ }
45
+ function prefixRoute(route, prefix) {
46
+ if (!route.path) {
47
+ return route;
48
+ }
49
+ return {
50
+ ...route,
51
+ path: `${prefix}${route.path}`
52
+ };
53
+ }
54
+ function unshiftTagRoute(route, tags) {
55
+ return {
56
+ ...route,
57
+ tags: [...tags, ...route.tags ?? []]
58
+ };
59
+ }
60
+ function mergePrefix(a, b) {
61
+ return a ? `${a}${b}` : b;
62
+ }
63
+ function mergeTags(a, b) {
64
+ return a ? [...a, ...b] : b;
65
+ }
66
+ function enhanceRoute(route, options) {
67
+ let router = route;
68
+ if (options.prefix) {
69
+ router = prefixRoute(router, options.prefix);
70
+ }
71
+ if (options.tags?.length) {
72
+ router = unshiftTagRoute(router, options.tags);
73
+ }
74
+ return router;
75
+ }
76
+
77
+ function getContractRouter(router, path) {
78
+ let current = router;
79
+ for (let i = 0; i < path.length; i++) {
80
+ const segment = path[i];
81
+ if (!current) {
82
+ return void 0;
83
+ }
84
+ if (isContractProcedure(current)) {
85
+ return void 0;
86
+ }
87
+ current = current[segment];
88
+ }
89
+ return current;
90
+ }
91
+ function enhanceContractRouter(router, options) {
92
+ if (isContractProcedure(router)) {
93
+ const enhanced2 = new ContractProcedure({
94
+ ...router["~orpc"],
95
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
96
+ route: enhanceRoute(router["~orpc"].route, options)
97
+ });
98
+ return enhanced2;
99
+ }
100
+ const enhanced = {};
101
+ for (const key in router) {
102
+ enhanced[key] = enhanceContractRouter(router[key], options);
103
+ }
104
+ return enhanced;
105
+ }
106
+ function minifyContractRouter(router) {
107
+ if (isContractProcedure(router)) {
108
+ const procedure = {
109
+ "~orpc": {
110
+ errorMap: {},
111
+ meta: router["~orpc"].meta,
112
+ route: router["~orpc"].route
113
+ }
114
+ };
115
+ return procedure;
116
+ }
117
+ const json = {};
118
+ for (const key in router) {
119
+ json[key] = minifyContractRouter(router[key]);
120
+ }
121
+ return json;
122
+ }
123
+
124
+ class ContractBuilder extends ContractProcedure {
125
+ constructor(def) {
126
+ super(def);
127
+ this["~orpc"].prefix = def.prefix;
128
+ this["~orpc"].tags = def.tags;
129
+ }
130
+ /**
131
+ * Sets or overrides the initial meta.
132
+ *
133
+ * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
134
+ */
135
+ $meta(initialMeta) {
136
+ return new ContractBuilder({
137
+ ...this["~orpc"],
138
+ meta: initialMeta
139
+ });
140
+ }
141
+ /**
142
+ * Sets or overrides the initial route.
143
+ * This option is typically relevant when integrating with OpenAPI.
144
+ *
145
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
146
+ * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
147
+ */
148
+ $route(initialRoute) {
149
+ return new ContractBuilder({
150
+ ...this["~orpc"],
151
+ route: initialRoute
152
+ });
153
+ }
154
+ /**
155
+ * Adds type-safe custom errors to the contract.
156
+ * The provided errors are spared-merged with any existing errors in the contract.
157
+ *
158
+ * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
159
+ */
160
+ errors(errors) {
161
+ return new ContractBuilder({
162
+ ...this["~orpc"],
163
+ errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
164
+ });
165
+ }
166
+ /**
167
+ * Sets or updates the metadata for the contract.
168
+ * The provided metadata is spared-merged with any existing metadata in the contract.
169
+ *
170
+ * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
171
+ */
172
+ meta(meta) {
173
+ return new ContractBuilder({
174
+ ...this["~orpc"],
175
+ meta: mergeMeta(this["~orpc"].meta, meta)
176
+ });
177
+ }
178
+ /**
179
+ * Sets or updates the route definition for the contract.
180
+ * The provided route is spared-merged with any existing route in the contract.
181
+ * This option is typically relevant when integrating with OpenAPI.
182
+ *
183
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
184
+ * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
185
+ */
186
+ route(route) {
187
+ return new ContractBuilder({
188
+ ...this["~orpc"],
189
+ route: mergeRoute(this["~orpc"].route, route)
190
+ });
191
+ }
192
+ /**
193
+ * Defines the input validation schema for the contract.
194
+ *
195
+ * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Input Validation Docs}
196
+ */
197
+ input(schema) {
198
+ return new ContractBuilder({
199
+ ...this["~orpc"],
200
+ inputSchema: schema
201
+ });
202
+ }
203
+ /**
204
+ * Defines the output validation schema for the contract.
205
+ *
206
+ * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Output Validation Docs}
207
+ */
208
+ output(schema) {
209
+ return new ContractBuilder({
210
+ ...this["~orpc"],
211
+ outputSchema: schema
212
+ });
213
+ }
214
+ /**
215
+ * Prefixes all procedures in the contract router.
216
+ * The provided prefix is post-appended to any existing router prefix.
217
+ *
218
+ * @note This option does not affect procedures that do not define a path in their route definition.
219
+ *
220
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing#route-prefixes OpenAPI Route Prefixes Docs}
221
+ */
222
+ prefix(prefix) {
223
+ return new ContractBuilder({
224
+ ...this["~orpc"],
225
+ prefix: mergePrefix(this["~orpc"].prefix, prefix)
226
+ });
227
+ }
228
+ /**
229
+ * Adds tags to all procedures in the contract router.
230
+ * This helpful when you want to group procedures together in the OpenAPI specification.
231
+ *
232
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification#operation-metadata OpenAPI Operation Metadata Docs}
233
+ */
234
+ tag(...tags) {
235
+ return new ContractBuilder({
236
+ ...this["~orpc"],
237
+ tags: mergeTags(this["~orpc"].tags, tags)
238
+ });
239
+ }
240
+ /**
241
+ * Applies all of the previously defined options to the specified contract router.
242
+ *
243
+ * @see {@link https://orpc.unnoq.com/docs/router#extending-router Extending Router Docs}
244
+ */
245
+ router(router) {
246
+ return enhanceContractRouter(router, this["~orpc"]);
247
+ }
248
+ }
249
+ const oc = new ContractBuilder({
250
+ errorMap: {},
251
+ route: {},
252
+ meta: {}
253
+ });
254
+
255
+ const DEFAULT_CONFIG = {
256
+ defaultMethod: "POST",
257
+ defaultSuccessStatus: 200,
258
+ defaultSuccessDescription: "OK",
259
+ defaultInputStructure: "compact",
260
+ defaultOutputStructure: "compact"
261
+ };
262
+ function fallbackContractConfig(key, value) {
263
+ if (value === void 0) {
264
+ return DEFAULT_CONFIG[key];
265
+ }
266
+ return value;
267
+ }
268
+
269
+ const EVENT_ITERATOR_DETAILS_SYMBOL = Symbol("ORPC_EVENT_ITERATOR_DETAILS");
270
+ function eventIterator(yields, returns) {
271
+ return {
272
+ "~standard": {
273
+ [EVENT_ITERATOR_DETAILS_SYMBOL]: { yields, returns },
274
+ vendor: "orpc",
275
+ version: 1,
276
+ validate(iterator) {
277
+ if (!isAsyncIteratorObject(iterator)) {
278
+ return { issues: [{ message: "Expect event iterator", path: [] }] };
279
+ }
280
+ const mapped = mapEventIterator(iterator, {
281
+ async value(value, done) {
282
+ const schema = done ? returns : yields;
283
+ if (!schema) {
284
+ return value;
285
+ }
286
+ const result = await schema["~standard"].validate(value);
287
+ if (result.issues) {
288
+ throw new ORPCError("EVENT_ITERATOR_VALIDATION_FAILED", {
289
+ message: "Event iterator validation failed",
290
+ cause: new ValidationError({
291
+ issues: result.issues,
292
+ message: "Event iterator validation failed"
293
+ })
294
+ });
295
+ }
296
+ return result.value;
297
+ },
298
+ error: async (error) => error
299
+ });
300
+ return { value: mapped };
301
+ }
302
+ }
303
+ };
304
+ }
305
+ function getEventIteratorSchemaDetails(schema) {
306
+ if (schema === void 0) {
307
+ return void 0;
308
+ }
309
+ return schema["~standard"][EVENT_ITERATOR_DETAILS_SYMBOL];
310
+ }
311
+
312
+ function inferRPCMethodFromContractRouter(contract) {
313
+ return (_, path) => {
314
+ const procedure = get(contract, path);
315
+ if (!isContractProcedure(procedure)) {
316
+ throw new Error(
317
+ `[inferRPCMethodFromContractRouter] No valid procedure found at path "${path.join(".")}". This may happen when the contract router is not properly configured.`
318
+ );
319
+ }
320
+ const method = fallbackContractConfig("defaultMethod", procedure["~orpc"].route.method);
321
+ return method === "HEAD" ? "GET" : method;
322
+ };
323
+ }
324
+
325
+ function type(...[map]) {
326
+ return {
327
+ "~standard": {
328
+ vendor: "custom",
329
+ version: 1,
330
+ async validate(value) {
331
+ if (map) {
332
+ return { value: await map(value) };
333
+ }
334
+ return { value };
335
+ }
336
+ }
337
+ };
338
+ }
339
+
340
+ function isSchemaIssue(issue) {
341
+ if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
342
+ return false;
343
+ }
344
+ if (issue.path !== void 0) {
345
+ if (!Array.isArray(issue.path)) {
346
+ return false;
347
+ }
348
+ if (!issue.path.every((segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key))) {
349
+ return false;
350
+ }
351
+ }
352
+ return true;
353
+ }
354
+
355
+ export { ContractBuilder, ContractProcedure, ValidationError, enhanceContractRouter, enhanceRoute, eventIterator, fallbackContractConfig, getContractRouter, getEventIteratorSchemaDetails, inferRPCMethodFromContractRouter, isContractProcedure, isSchemaIssue, mergeErrorMap, mergeMeta, mergePrefix, mergeRoute, mergeTags, minifyContractRouter, oc, prefixRoute, type, unshiftTagRoute };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/contract",
3
3
  "type": "module",
4
- "version": "0.0.0-next.fe39bf3",
4
+ "version": "0.0.0-next.fe5c63f",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,32 +15,27 @@
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
- "./🔒/*": {
23
- "types": "./dist/src/*.d.ts"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
24
21
  }
25
22
  },
26
23
  "files": [
27
- "!**/*.map",
28
- "!**/*.tsbuildinfo",
29
24
  "dist"
30
25
  ],
31
26
  "dependencies": {
32
- "@orpc/server-standard": "^0.4.0",
33
27
  "@standard-schema/spec": "^1.0.0",
34
- "@orpc/client": "0.0.0-next.fe39bf3",
35
- "@orpc/shared": "0.0.0-next.fe39bf3"
28
+ "openapi-types": "^12.1.3",
29
+ "@orpc/client": "0.0.0-next.fe5c63f",
30
+ "@orpc/shared": "0.0.0-next.fe5c63f"
36
31
  },
37
32
  "devDependencies": {
38
- "arktype": "2.0.0-rc.26",
39
- "valibot": "1.0.0-beta.9",
40
- "zod": "^3.24.1"
33
+ "arktype": "2.1.20",
34
+ "valibot": "^1.1.0",
35
+ "zod": "^4.0.5"
41
36
  },
42
37
  "scripts": {
43
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
38
+ "build": "unbuild",
44
39
  "build:watch": "pnpm run build --watch",
45
40
  "type:check": "tsc -b"
46
41
  }
package/dist/index.js DELETED
@@ -1,270 +0,0 @@
1
- // src/error.ts
2
- var ValidationError = class extends Error {
3
- issues;
4
- constructor(options) {
5
- super(options.message, options);
6
- this.issues = options.issues;
7
- }
8
- };
9
- function mergeErrorMap(errorMap1, errorMap2) {
10
- return { ...errorMap1, ...errorMap2 };
11
- }
12
-
13
- // src/meta.ts
14
- function mergeMeta(meta1, meta2) {
15
- return { ...meta1, ...meta2 };
16
- }
17
-
18
- // src/procedure.ts
19
- var ContractProcedure = class {
20
- "~orpc";
21
- constructor(def) {
22
- if (def.route?.successStatus && (def.route.successStatus < 200 || def.route?.successStatus > 299)) {
23
- throw new Error("[ContractProcedure] The successStatus must be between 200 and 299");
24
- }
25
- if (Object.values(def.errorMap).some((val) => val && val.status && (val.status < 400 || val.status > 599))) {
26
- throw new Error("[ContractProcedure] The error status code must be in the 400-599 range.");
27
- }
28
- this["~orpc"] = def;
29
- }
30
- };
31
- function isContractProcedure(item) {
32
- if (item instanceof ContractProcedure) {
33
- return true;
34
- }
35
- return (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "inputSchema" in item["~orpc"] && "outputSchema" in item["~orpc"] && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
36
- }
37
-
38
- // src/route.ts
39
- function mergeRoute(a, b) {
40
- return { ...a, ...b };
41
- }
42
- function prefixRoute(route, prefix) {
43
- if (!route.path) {
44
- return route;
45
- }
46
- return {
47
- ...route,
48
- path: `${prefix}${route.path}`
49
- };
50
- }
51
- function unshiftTagRoute(route, tags) {
52
- return {
53
- ...route,
54
- tags: [...tags, ...route.tags ?? []]
55
- };
56
- }
57
- function mergePrefix(a, b) {
58
- return a ? `${a}${b}` : b;
59
- }
60
- function mergeTags(a, b) {
61
- return a ? [...a, ...b] : b;
62
- }
63
- function adaptRoute(route, options) {
64
- let router = route;
65
- if (options.prefix) {
66
- router = prefixRoute(router, options.prefix);
67
- }
68
- if (options.tags) {
69
- router = unshiftTagRoute(router, options.tags);
70
- }
71
- return router;
72
- }
73
-
74
- // src/router.ts
75
- function adaptContractRouter(contract, options) {
76
- if (isContractProcedure(contract)) {
77
- const adapted2 = new ContractProcedure({
78
- ...contract["~orpc"],
79
- errorMap: mergeErrorMap(options.errorMap, contract["~orpc"].errorMap),
80
- route: adaptRoute(contract["~orpc"].route, options)
81
- });
82
- return adapted2;
83
- }
84
- const adapted = {};
85
- for (const key in contract) {
86
- adapted[key] = adaptContractRouter(contract[key], options);
87
- }
88
- return adapted;
89
- }
90
-
91
- // src/builder.ts
92
- var ContractBuilder = class _ContractBuilder extends ContractProcedure {
93
- constructor(def) {
94
- super(def);
95
- this["~orpc"].prefix = def.prefix;
96
- this["~orpc"].tags = def.tags;
97
- }
98
- /**
99
- * Reset initial meta
100
- */
101
- $meta(initialMeta) {
102
- return new _ContractBuilder({
103
- ...this["~orpc"],
104
- meta: initialMeta
105
- });
106
- }
107
- /**
108
- * Reset initial route
109
- */
110
- $route(initialRoute) {
111
- return new _ContractBuilder({
112
- ...this["~orpc"],
113
- route: initialRoute
114
- });
115
- }
116
- errors(errors) {
117
- return new _ContractBuilder({
118
- ...this["~orpc"],
119
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
120
- });
121
- }
122
- meta(meta) {
123
- return new _ContractBuilder({
124
- ...this["~orpc"],
125
- meta: mergeMeta(this["~orpc"].meta, meta)
126
- });
127
- }
128
- route(route) {
129
- return new _ContractBuilder({
130
- ...this["~orpc"],
131
- route: mergeRoute(this["~orpc"].route, route)
132
- });
133
- }
134
- input(schema) {
135
- return new _ContractBuilder({
136
- ...this["~orpc"],
137
- inputSchema: schema
138
- });
139
- }
140
- output(schema) {
141
- return new _ContractBuilder({
142
- ...this["~orpc"],
143
- outputSchema: schema
144
- });
145
- }
146
- prefix(prefix) {
147
- return new _ContractBuilder({
148
- ...this["~orpc"],
149
- prefix: mergePrefix(this["~orpc"].prefix, prefix)
150
- });
151
- }
152
- tag(...tags) {
153
- return new _ContractBuilder({
154
- ...this["~orpc"],
155
- tags: mergeTags(this["~orpc"].tags, tags)
156
- });
157
- }
158
- router(router) {
159
- return adaptContractRouter(router, this["~orpc"]);
160
- }
161
- };
162
- var oc = new ContractBuilder({
163
- errorMap: {},
164
- inputSchema: void 0,
165
- outputSchema: void 0,
166
- route: {},
167
- meta: {}
168
- });
169
-
170
- // src/config.ts
171
- var DEFAULT_CONFIG = {
172
- defaultMethod: "POST",
173
- defaultSuccessStatus: 200,
174
- defaultSuccessDescription: "OK",
175
- defaultInputStructure: "compact",
176
- defaultOutputStructure: "compact"
177
- };
178
- function fallbackContractConfig(key, value) {
179
- if (value === void 0) {
180
- return DEFAULT_CONFIG[key];
181
- }
182
- return value;
183
- }
184
-
185
- // src/event-iterator.ts
186
- import { mapEventIterator, ORPCError } from "@orpc/client";
187
- import { isAsyncIteratorObject } from "@orpc/server-standard";
188
- var EVENT_ITERATOR_SCHEMA_SYMBOL = Symbol("ORPC_EVENT_ITERATOR_SCHEMA");
189
- function eventIterator(yields, returns) {
190
- return {
191
- "~standard": {
192
- [EVENT_ITERATOR_SCHEMA_SYMBOL]: { yields, returns },
193
- vendor: "orpc",
194
- version: 1,
195
- validate(iterator) {
196
- if (!isAsyncIteratorObject(iterator)) {
197
- return { issues: [{ message: "Expect event source iterator", path: [] }] };
198
- }
199
- const mapped = mapEventIterator(iterator, {
200
- async value(value, done) {
201
- const schema = done ? returns : yields;
202
- if (!schema) {
203
- return value;
204
- }
205
- const result = await schema["~standard"].validate(value);
206
- if (result.issues) {
207
- throw new ORPCError("EVENT_ITERATOR_VALIDATION_FAILED", {
208
- message: "Event source iterator validation failed",
209
- cause: new ValidationError({
210
- issues: result.issues,
211
- message: "Event source iterator validation failed"
212
- })
213
- });
214
- }
215
- return result.value;
216
- },
217
- error: async (error) => error
218
- });
219
- return { value: mapped };
220
- }
221
- }
222
- };
223
- }
224
- function getEventIteratorSchemaDetails(schema) {
225
- if (schema === void 0) {
226
- return void 0;
227
- }
228
- return schema["~standard"][EVENT_ITERATOR_SCHEMA_SYMBOL];
229
- }
230
-
231
- // src/schema.ts
232
- function type(...[map]) {
233
- return {
234
- "~standard": {
235
- vendor: "custom",
236
- version: 1,
237
- async validate(value) {
238
- if (map) {
239
- return { value: await map(value) };
240
- }
241
- return { value };
242
- }
243
- }
244
- };
245
- }
246
-
247
- // src/index.ts
248
- import { ORPCError as ORPCError2 } from "@orpc/client";
249
- export {
250
- ContractBuilder,
251
- ContractProcedure,
252
- ORPCError2 as ORPCError,
253
- ValidationError,
254
- adaptContractRouter,
255
- adaptRoute,
256
- eventIterator,
257
- fallbackContractConfig,
258
- getEventIteratorSchemaDetails,
259
- isContractProcedure,
260
- mergeErrorMap,
261
- mergeMeta,
262
- mergePrefix,
263
- mergeRoute,
264
- mergeTags,
265
- oc,
266
- prefixRoute,
267
- type,
268
- unshiftTagRoute
269
- };
270
- //# sourceMappingURL=index.js.map