@orpc/openapi 1.14.5 → 2.0.0-beta.1

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.
Files changed (48) hide show
  1. package/README.md +75 -109
  2. package/dist/adapters/fetch/index.d.mts +20 -16
  3. package/dist/adapters/fetch/index.d.ts +20 -16
  4. package/dist/adapters/fetch/index.mjs +24 -8
  5. package/dist/adapters/node/index.d.mts +8 -13
  6. package/dist/adapters/node/index.d.ts +8 -13
  7. package/dist/adapters/node/index.mjs +10 -7
  8. package/dist/adapters/standard/index.d.mts +46 -16
  9. package/dist/adapters/standard/index.d.ts +46 -16
  10. package/dist/adapters/standard/index.mjs +9 -6
  11. package/dist/extensions/route.d.mts +43 -0
  12. package/dist/extensions/route.d.ts +43 -0
  13. package/dist/extensions/route.mjs +14 -0
  14. package/dist/helpers/index.d.mts +51 -0
  15. package/dist/helpers/index.d.ts +51 -0
  16. package/dist/helpers/index.mjs +39 -0
  17. package/dist/index.d.mts +92 -111
  18. package/dist/index.d.ts +92 -111
  19. package/dist/index.mjs +894 -34
  20. package/dist/plugins/index.d.mts +55 -51
  21. package/dist/plugins/index.d.ts +55 -51
  22. package/dist/plugins/index.mjs +147 -142
  23. package/dist/shared/openapi.B2SK0ZAr.mjs +359 -0
  24. package/dist/shared/openapi.B9PQzqBn.mjs +49 -0
  25. package/dist/shared/openapi.BQzzr4-4.d.ts +299 -0
  26. package/dist/shared/openapi.BcEtAxQj.d.mts +299 -0
  27. package/dist/shared/openapi.Bt87OzTt.mjs +131 -0
  28. package/dist/shared/openapi.C7m7NAmH.d.mts +142 -0
  29. package/dist/shared/openapi.C7m7NAmH.d.ts +142 -0
  30. package/dist/shared/openapi.C9Olbxd5.d.ts +75 -0
  31. package/dist/shared/openapi.CYgMBSUF.d.mts +18 -0
  32. package/dist/shared/openapi.CYgMBSUF.d.ts +18 -0
  33. package/dist/shared/openapi.CcyUEuTs.mjs +313 -0
  34. package/dist/shared/openapi.DmAa7YPO.mjs +275 -0
  35. package/dist/shared/openapi.Drd1OtzG.d.mts +75 -0
  36. package/package.json +29 -23
  37. package/dist/adapters/aws-lambda/index.d.mts +0 -20
  38. package/dist/adapters/aws-lambda/index.d.ts +0 -20
  39. package/dist/adapters/aws-lambda/index.mjs +0 -18
  40. package/dist/adapters/fastify/index.d.mts +0 -23
  41. package/dist/adapters/fastify/index.d.ts +0 -23
  42. package/dist/adapters/fastify/index.mjs +0 -18
  43. package/dist/shared/openapi.BB-W-NKv.mjs +0 -204
  44. package/dist/shared/openapi.BGy4N6eR.d.mts +0 -120
  45. package/dist/shared/openapi.BGy4N6eR.d.ts +0 -120
  46. package/dist/shared/openapi.BwdtJjDu.mjs +0 -878
  47. package/dist/shared/openapi.DwaweYRb.d.mts +0 -54
  48. package/dist/shared/openapi.DwaweYRb.d.ts +0 -54
@@ -0,0 +1,359 @@
1
+ import { isORPCErrorJson, createORPCErrorFromJson, ORPCError } from '@orpc/client';
2
+ import { getRouterContract, ProcedureContract } from '@orpc/contract';
3
+ import { unlazy } from '@orpc/server';
4
+ import { value, pathToHttpPath, mergeHttpPath, isTypescriptObject, stringifyJSON } from '@orpc/shared';
5
+ import { mergeStandardHeaders, parseStandardUrl, isStandardHeaders } from '@standardserver/core';
6
+ import { toStandardHeaders } from '@standardserver/fetch';
7
+ import { O as OpenAPISerializer, D as DEFAULT_OPENAPI_METHOD, a as DEFAULT_OPENAPI_INPUT_STRUCTURE, g as getDynamicPathParams, b as DEFAULT_OPENAPI_OUTPUT_STRUCTURE } from './openapi.DmAa7YPO.mjs';
8
+ import { g as getOpenAPIMeta } from './openapi.B9PQzqBn.mjs';
9
+
10
+ class OpenAPILinkCodecError extends TypeError {
11
+ }
12
+ const END_SLASH_REGEX = /\/$/;
13
+ class OpenAPILinkCodec {
14
+ constructor(router, options = {}) {
15
+ this.router = router;
16
+ this.baseUrl = options.url ?? "/";
17
+ this.headers = options.headers ?? {};
18
+ this.serializer = options.serializer ?? new OpenAPISerializer();
19
+ this.customErrorResponseBodyDecoder = options.customErrorResponseBodyDecoder;
20
+ }
21
+ baseUrl;
22
+ headers;
23
+ serializer;
24
+ customErrorResponseBodyDecoder;
25
+ async encodeInput(input, path, options) {
26
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
27
+ if (options.lastEventId !== void 0) {
28
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
29
+ }
30
+ const baseUrl = await value(this.baseUrl, options, path, input);
31
+ const procedure = await this.resolveProcedure(path);
32
+ const meta = getOpenAPIMeta(procedure);
33
+ const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
34
+ const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
35
+ let pathname = meta?.path ?? pathToHttpPath(path);
36
+ if (meta?.prefix) {
37
+ pathname = mergeHttpPath(meta.prefix, pathname);
38
+ }
39
+ const [basePathname, baseSearch, baseHash] = parseStandardUrl(baseUrl);
40
+ const dynamicParams = getDynamicPathParams(pathname);
41
+ if (inputStructure === "compact") {
42
+ let data = input;
43
+ if (dynamicParams?.length) {
44
+ if (!isTypescriptObject(input)) {
45
+ throw new OpenAPILinkCodecError(
46
+ `Input must be an object with "compact" input structure when the path has dynamic params (${dynamicParams.map((p) => p.parameterName).join(", ")}) in call to procedure (${path.join(".")}).`
47
+ );
48
+ }
49
+ const remaining = { ...input };
50
+ for (let i = dynamicParams.length - 1; i >= 0; i--) {
51
+ const param = dynamicParams[i];
52
+ const encoded = this.encodePathParam(input[param.parameterName], param, meta?.paramsStyles?.[param.parameterName], path);
53
+ pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
54
+ delete remaining[param.parameterName];
55
+ }
56
+ data = Object.keys(remaining).length > 0 ? remaining : void 0;
57
+ }
58
+ pathname = `${basePathname.replace(END_SLASH_REGEX, "")}${pathname}`;
59
+ if (method === "GET") {
60
+ const queryString2 = this.serializeQueryString(data, meta?.queryStyles);
61
+ const search2 = combineSearch(baseSearch, queryString2);
62
+ const url3 = `${pathname}${search2 ?? ""}${baseHash ?? ""}`;
63
+ return {
64
+ body: void 0,
65
+ method,
66
+ headers,
67
+ url: url3,
68
+ signal: options.signal
69
+ };
70
+ }
71
+ const url2 = `${pathname}${baseSearch ?? ""}${baseHash ?? ""}`;
72
+ return {
73
+ url: url2,
74
+ method,
75
+ headers,
76
+ body: this.serializer.serialize(data),
77
+ signal: options.signal
78
+ };
79
+ }
80
+ if (!isValidDetailedInput(input)) {
81
+ throw new OpenAPILinkCodecError(`
82
+ Invalid "detailed" input structure in call to procedure (${path.join(".")}):
83
+ \u2022 Expected an object or undefined with optional properties:
84
+ - params (object, required when the path has dynamic params)
85
+ - query (object)
86
+ - headers (Record<string, string | string[] | undefined>)
87
+ - body (any)
88
+
89
+ Actual value:
90
+ ${stringifyJSON(input)}
91
+ `);
92
+ }
93
+ if (dynamicParams?.length) {
94
+ if (!input?.params) {
95
+ throw new OpenAPILinkCodecError(
96
+ `The "params" property is required for "detailed" input when the path has dynamic params (${dynamicParams.map((p) => p.parameterName).join(", ")}) in call to procedure (${path.join(".")}).`
97
+ );
98
+ }
99
+ for (let i = dynamicParams.length - 1; i >= 0; i--) {
100
+ const param = dynamicParams[i];
101
+ const val = input.params[param.parameterName];
102
+ const encoded = this.encodePathParam(val, param, meta?.paramsStyles?.[param.parameterName], path);
103
+ pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
104
+ }
105
+ }
106
+ if (input?.headers) {
107
+ headers = mergeStandardHeaders(headers, input.headers);
108
+ }
109
+ pathname = `${basePathname.replace(END_SLASH_REGEX, "")}${pathname}`;
110
+ const queryString = this.serializeQueryString(input?.query, meta?.queryStyles);
111
+ const search = combineSearch(baseSearch, queryString);
112
+ const url = `${pathname}${search ?? ""}${baseHash ?? ""}`;
113
+ if (method === "GET") {
114
+ return {
115
+ body: void 0,
116
+ method,
117
+ headers,
118
+ url,
119
+ signal: options.signal
120
+ };
121
+ }
122
+ return {
123
+ url,
124
+ method,
125
+ headers,
126
+ body: this.serializer.serialize(input?.body),
127
+ signal: options.signal
128
+ };
129
+ }
130
+ encodePathParam(val, param, style, path) {
131
+ let encoded;
132
+ if (style === "comma-delimited-array" && Array.isArray(val)) {
133
+ encoded = val.map((val2) => this.serializer.serialize(val2)).filter((val2) => val2 !== void 0 && val2 !== null).map((val2) => encodeURIComponent(String(val2))).join(",");
134
+ } else if (style === "comma-delimited-object" && isTypescriptObject(val)) {
135
+ encoded = Object.entries(val).map(([key, val2]) => [key, this.serializer.serialize(val2)]).filter(([, val2]) => val2 !== void 0 && val2 !== null).map(([key, val2]) => `${encodeURIComponent(String(key))},${encodeURIComponent(String(val2))}`).join(",");
136
+ } else {
137
+ const serialized = this.serializer.serialize(val);
138
+ if (serialized !== void 0 && serialized !== null) {
139
+ if (param.allowsSlash) {
140
+ encoded = String(serialized).split("/").map(encodeURIComponent).join("/");
141
+ } else {
142
+ encoded = encodeURIComponent(String(serialized));
143
+ }
144
+ }
145
+ }
146
+ if (!encoded) {
147
+ throw new OpenAPILinkCodecError(`Path param "${param.parameterName}" cannot be empty in call to procedure (${path.join(".")}).`);
148
+ }
149
+ return encoded;
150
+ }
151
+ serializeQueryString(data, queryStyles) {
152
+ if (!queryStyles || !isTypescriptObject(data)) {
153
+ return toURLSearchParams(
154
+ this.serializer.serialize(data, { asFormData: true })
155
+ ).toString();
156
+ }
157
+ const remaining = { ...data };
158
+ let query = "";
159
+ Object.entries(queryStyles).forEach(([key, style]) => {
160
+ if (style === void 0) {
161
+ return;
162
+ }
163
+ const value2 = remaining[key];
164
+ delete remaining[key];
165
+ if (style === "primitive") {
166
+ const serialized = this.serializer.serialize(value2);
167
+ if (serialized !== void 0 && serialized !== null) {
168
+ query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
169
+ }
170
+ } else if (style === "array" && Array.isArray(value2)) {
171
+ const encodedKey = encodeURLSearchParamComponent(key);
172
+ value2.forEach((v) => {
173
+ const s = this.serializer.serialize(v);
174
+ if (s !== void 0 && s !== null) {
175
+ query += `&${encodedKey}=${encodeURLSearchParamComponent(String(s))}`;
176
+ }
177
+ });
178
+ } else if (style === "json") {
179
+ const serialized = this.serializer.serialize(value2);
180
+ if (serialized !== void 0) {
181
+ query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(stringifyJSON(serialized))}`;
182
+ }
183
+ } else if (style === "comma-delimited-array" && Array.isArray(value2)) {
184
+ const encodedValue = encodeDelimitedArray(
185
+ value2.map((v) => this.serializer.serialize(v)),
186
+ ","
187
+ );
188
+ if (encodedValue !== void 0) {
189
+ query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
190
+ }
191
+ } else if (style === "comma-delimited-object" && isTypescriptObject(value2)) {
192
+ const encodedValue = encodeDelimitedObject(
193
+ Object.entries(value2).map(([key2, value3]) => [key2, this.serializer.serialize(value3)]),
194
+ ","
195
+ );
196
+ if (encodedValue !== void 0) {
197
+ query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
198
+ }
199
+ } else if (style === "pipe-delimited-array" && Array.isArray(value2)) {
200
+ const encodedValue = encodeDelimitedArray(
201
+ value2.map((v) => this.serializer.serialize(v)),
202
+ "%7C"
203
+ );
204
+ if (encodedValue !== void 0) {
205
+ query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
206
+ }
207
+ } else if (style === "pipe-delimited-object" && isTypescriptObject(value2)) {
208
+ const encodedValue = encodeDelimitedObject(
209
+ Object.entries(value2).map(([key2, value3]) => [key2, this.serializer.serialize(value3)]),
210
+ "%7C"
211
+ );
212
+ if (encodedValue !== void 0) {
213
+ query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
214
+ }
215
+ } else if (style === "space-delimited-array" && Array.isArray(value2)) {
216
+ const encodedValue = encodeDelimitedArray(
217
+ value2.map((v) => this.serializer.serialize(v)),
218
+ "%20"
219
+ );
220
+ if (encodedValue !== void 0) {
221
+ query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
222
+ }
223
+ } else if (style === "space-delimited-object" && isTypescriptObject(value2)) {
224
+ const encodedValue = encodeDelimitedObject(
225
+ Object.entries(value2).map(([key2, value3]) => [key2, this.serializer.serialize(value3)]),
226
+ "%20"
227
+ );
228
+ if (encodedValue !== void 0) {
229
+ query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
230
+ }
231
+ } else {
232
+ const serialized = this.serializer.serialize(value2);
233
+ if (serialized !== void 0 && serialized !== null) {
234
+ query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
235
+ }
236
+ }
237
+ });
238
+ const form = this.serializer.serialize(remaining, { asFormData: true });
239
+ query = `${toURLSearchParams(form).toString()}${query}`;
240
+ if (query.startsWith("&")) {
241
+ query = query.slice(1);
242
+ }
243
+ return query || void 0;
244
+ }
245
+ async decodeResponse(response, path, _options) {
246
+ const isOk = response.status >= 200 && response.status < 400;
247
+ const procedure = await this.resolveProcedure(path);
248
+ const meta = getOpenAPIMeta(procedure);
249
+ const deserialized = await (async () => {
250
+ let isBodyOk = false;
251
+ try {
252
+ const body = await response.resolveBody(meta?.responseBodyHint);
253
+ isBodyOk = true;
254
+ return this.serializer.deserialize(body);
255
+ } catch (error) {
256
+ if (!isBodyOk) {
257
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
258
+ cause: error
259
+ });
260
+ }
261
+ throw new Error("Invalid OpenAPI response format.", {
262
+ cause: error
263
+ });
264
+ }
265
+ })();
266
+ if (!isOk) {
267
+ const customError = this.customErrorResponseBodyDecoder?.(deserialized, response);
268
+ if (customError !== void 0 && customError !== null) {
269
+ return { kind: "error", error: customError };
270
+ }
271
+ if (isORPCErrorJson(deserialized)) {
272
+ return { kind: "error", error: createORPCErrorFromJson(deserialized) };
273
+ }
274
+ return {
275
+ kind: "error",
276
+ error: new ORPCError("MALFORMED_ORPC_ERROR_RESPONSE", {
277
+ data: { headers: response.headers, status: response.status, body: deserialized }
278
+ })
279
+ };
280
+ }
281
+ const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
282
+ return outputStructure === "compact" ? { kind: "output", output: deserialized } : {
283
+ kind: "output",
284
+ output: {
285
+ status: response.status,
286
+ headers: response.headers,
287
+ body: deserialized
288
+ }
289
+ };
290
+ }
291
+ async resolveProcedure(path) {
292
+ const { default: maybeProcedure } = await unlazy(getRouterContract(this.router, path));
293
+ if (!(maybeProcedure instanceof ProcedureContract)) {
294
+ throw new OpenAPILinkCodecError(`Expected a procedure or contract at path (${path.join(".")})`);
295
+ }
296
+ return maybeProcedure;
297
+ }
298
+ }
299
+ function combineSearch(baseSearch, additionalSearch) {
300
+ if (!baseSearch && !additionalSearch) {
301
+ return void 0;
302
+ }
303
+ if (!additionalSearch) {
304
+ return baseSearch;
305
+ }
306
+ if (!baseSearch) {
307
+ return `?${additionalSearch}`;
308
+ }
309
+ return `${baseSearch}&${additionalSearch}`;
310
+ }
311
+ function toResolvedStandardHeaders(headers) {
312
+ if (typeof headers.forEach === "function") {
313
+ return toStandardHeaders(headers);
314
+ }
315
+ return headers;
316
+ }
317
+ function isValidDetailedInput(input) {
318
+ if (!isTypescriptObject(input)) {
319
+ return input === void 0;
320
+ }
321
+ if (input.params !== void 0 && !isTypescriptObject(input.params)) {
322
+ return false;
323
+ }
324
+ if (input.query !== void 0 && !isTypescriptObject(input.query)) {
325
+ return false;
326
+ }
327
+ if (input.headers !== void 0 && !isStandardHeaders(input.headers)) {
328
+ return false;
329
+ }
330
+ return true;
331
+ }
332
+ function encodeURLSearchParamComponent(value2) {
333
+ return new URLSearchParams({ "": value2 }).toString().slice(1);
334
+ }
335
+ function toURLSearchParams(form) {
336
+ const params = new URLSearchParams();
337
+ for (const [key, value2] of form) {
338
+ params.append(key, String(value2));
339
+ }
340
+ return params;
341
+ }
342
+ function encodeDelimitedArray(serializedValues, encodedDelimiter) {
343
+ const strings = serializedValues.filter((v) => v !== null && v !== void 0).map(String);
344
+ if (!strings.length) {
345
+ return void 0;
346
+ }
347
+ return strings.map(encodeURLSearchParamComponent).join(encodedDelimiter);
348
+ }
349
+ function encodeDelimitedObject(entries, encodedDelimiter) {
350
+ const strings = entries.filter(([v]) => v !== null && v !== void 0).map(([k, v]) => [k, String(v)]);
351
+ if (!strings.length) {
352
+ return void 0;
353
+ }
354
+ return strings.map(
355
+ ([key, value2]) => `${encodeURLSearchParamComponent(key)}${encodedDelimiter}${encodeURLSearchParamComponent(value2)}`
356
+ ).join(encodedDelimiter);
357
+ }
358
+
359
+ export { OpenAPILinkCodec as O, OpenAPILinkCodecError as a };
@@ -0,0 +1,49 @@
1
+ import { mergeHttpPath } from '@orpc/shared';
2
+
3
+ const openapi = (incoming) => ({
4
+ name: "~openapi",
5
+ init(meta) {
6
+ const existing = meta["~openapi"];
7
+ const tags = existing?.tags && incoming.tags ? [...existing.tags, ...incoming.tags] : "tags" in incoming ? incoming.tags : existing?.tags;
8
+ const queryStyles = existing?.queryStyles && incoming.queryStyles ? { ...existing.queryStyles, ...incoming.queryStyles } : "queryStyles" in incoming ? incoming.queryStyles : existing?.queryStyles;
9
+ const paramsStyles = existing?.paramsStyles && incoming.paramsStyles ? { ...existing.paramsStyles, ...incoming.paramsStyles } : "paramsStyles" in incoming ? incoming.paramsStyles : existing?.paramsStyles;
10
+ const existingSpec = existing?.spec;
11
+ const incomingSpec = incoming.spec;
12
+ const spec = typeof existingSpec === "function" && typeof incomingSpec === "function" ? (current) => incomingSpec(existingSpec(current)) : typeof existingSpec === "function" && typeof incomingSpec === "object" ? existingSpec(incomingSpec) : typeof existingSpec === "object" && typeof incomingSpec === "function" ? incomingSpec(existingSpec) : "spec" in incoming ? incomingSpec : existingSpec;
13
+ const prefix = existing?.prefix && incoming.prefix ? mergeHttpPath(existing.prefix, incoming.prefix) : "prefix" in incoming ? incoming.prefix : existing?.prefix;
14
+ const merged = {
15
+ ...existing,
16
+ ...incoming,
17
+ tags,
18
+ queryStyles,
19
+ paramsStyles,
20
+ spec,
21
+ prefix
22
+ };
23
+ return {
24
+ ...meta,
25
+ "~openapi": merged
26
+ };
27
+ }
28
+ });
29
+ openapi.method = (method) => ({
30
+ ...openapi({ method }),
31
+ name: "~openapi/method"
32
+ });
33
+ openapi.path = (path) => ({
34
+ ...openapi({ path }),
35
+ name: "~openapi/path"
36
+ });
37
+ openapi.spec = (spec) => ({
38
+ ...openapi({ spec }),
39
+ name: "~openapi/spec"
40
+ });
41
+ openapi.prefix = (prefix) => ({
42
+ ...openapi({ prefix }),
43
+ name: "~openapi/prefix"
44
+ });
45
+ function getOpenAPIMeta(procedureOrLazy) {
46
+ return procedureOrLazy["~orpc"].meta["~openapi"];
47
+ }
48
+
49
+ export { getOpenAPIMeta as g, openapi as o };