@orpc/contract 0.0.0-next.f22c7ec → 0.0.0-next.f437dcb

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