@orpc/openapi 0.40.0 → 0.41.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.
@@ -0,0 +1,165 @@
1
+ import {
2
+ standardizeHTTPPath
3
+ } from "./chunk-XGHV4TH3.js";
4
+
5
+ // src/adapters/standard/openapi-codec.ts
6
+ import { OpenAPISerializer } from "@orpc/client/openapi";
7
+ import { fallbackContractConfig } from "@orpc/contract";
8
+ import { isObject } from "@orpc/shared";
9
+ var OpenAPICodec = class {
10
+ serializer;
11
+ constructor(options) {
12
+ this.serializer = options?.serializer ?? new OpenAPISerializer();
13
+ }
14
+ async decode(request, params, procedure) {
15
+ const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
16
+ if (inputStructure === "compact") {
17
+ const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
18
+ if (data === void 0) {
19
+ return params;
20
+ }
21
+ if (isObject(data)) {
22
+ return {
23
+ ...params,
24
+ ...data
25
+ };
26
+ }
27
+ return data;
28
+ }
29
+ const deserializeSearchParams = () => {
30
+ return this.serializer.deserialize(request.url.searchParams);
31
+ };
32
+ return {
33
+ params,
34
+ get query() {
35
+ const value = deserializeSearchParams();
36
+ Object.defineProperty(this, "query", { value, writable: true });
37
+ return value;
38
+ },
39
+ set query(value) {
40
+ Object.defineProperty(this, "query", { value, writable: true });
41
+ },
42
+ headers: request.headers,
43
+ body: this.serializer.deserialize(await request.body())
44
+ };
45
+ }
46
+ encode(output, procedure) {
47
+ const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
48
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
49
+ if (outputStructure === "compact") {
50
+ return {
51
+ status: successStatus,
52
+ headers: {},
53
+ body: this.serializer.serialize(output)
54
+ };
55
+ }
56
+ if (!isObject(output)) {
57
+ throw new Error(
58
+ 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
59
+ );
60
+ }
61
+ return {
62
+ status: successStatus,
63
+ headers: output.headers ?? {},
64
+ body: this.serializer.serialize(output.body)
65
+ };
66
+ }
67
+ encodeError(error) {
68
+ return {
69
+ status: error.status,
70
+ headers: {},
71
+ body: this.serializer.serialize(error.toJSON())
72
+ };
73
+ }
74
+ };
75
+
76
+ // src/adapters/standard/openapi-matcher.ts
77
+ import { fallbackContractConfig as fallbackContractConfig2 } from "@orpc/contract";
78
+ import { convertPathToHttpPath, createContractedProcedure, eachContractProcedure, getLazyRouterPrefix, getRouterChild, isProcedure, unlazy } from "@orpc/server";
79
+ import { addRoute, createRouter, findRoute } from "rou3";
80
+ var OpenAPIMatcher = class {
81
+ tree = createRouter();
82
+ ignoreUndefinedMethod;
83
+ constructor(options) {
84
+ this.ignoreUndefinedMethod = options?.ignoreUndefinedMethod ?? false;
85
+ }
86
+ pendingRouters = [];
87
+ init(router, path = []) {
88
+ const laziedOptions = eachContractProcedure({
89
+ router,
90
+ path
91
+ }, ({ path: path2, contract }) => {
92
+ if (!contract["~orpc"].route.method && this.ignoreUndefinedMethod) {
93
+ return;
94
+ }
95
+ const method = fallbackContractConfig2("defaultMethod", contract["~orpc"].route.method);
96
+ const httpPath = contract["~orpc"].route.path ? toRou3Pattern(contract["~orpc"].route.path) : convertPathToHttpPath(path2);
97
+ if (isProcedure(contract)) {
98
+ addRoute(this.tree, method, httpPath, {
99
+ path: path2,
100
+ contract,
101
+ procedure: contract,
102
+ // this mean dev not used contract-first so we can used contract as procedure directly
103
+ router
104
+ });
105
+ } else {
106
+ addRoute(this.tree, method, httpPath, {
107
+ path: path2,
108
+ contract,
109
+ procedure: void 0,
110
+ router
111
+ });
112
+ }
113
+ });
114
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
115
+ ...option,
116
+ httpPathPrefix: convertPathToHttpPath(option.path),
117
+ laziedPrefix: getLazyRouterPrefix(option.lazied)
118
+ })));
119
+ }
120
+ async match(method, pathname) {
121
+ if (this.pendingRouters.length) {
122
+ const newPendingRouters = [];
123
+ for (const pendingRouter of this.pendingRouters) {
124
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
125
+ const { default: router } = await unlazy(pendingRouter.lazied);
126
+ this.init(router, pendingRouter.path);
127
+ } else {
128
+ newPendingRouters.push(pendingRouter);
129
+ }
130
+ }
131
+ this.pendingRouters = newPendingRouters;
132
+ }
133
+ const match = findRoute(this.tree, method, pathname);
134
+ if (!match) {
135
+ return void 0;
136
+ }
137
+ if (!match.data.procedure) {
138
+ const { default: maybeProcedure } = await unlazy(getRouterChild(match.data.router, ...match.data.path));
139
+ if (!isProcedure(maybeProcedure)) {
140
+ throw new Error(`
141
+ [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.data.path)}.
142
+ Ensure that the procedure is correctly defined and matches the expected contract.
143
+ `);
144
+ }
145
+ match.data.procedure = createContractedProcedure(match.data.contract, maybeProcedure);
146
+ }
147
+ return {
148
+ path: match.data.path,
149
+ procedure: match.data.procedure,
150
+ params: match.params ? decodeParams(match.params) : void 0
151
+ };
152
+ }
153
+ };
154
+ function toRou3Pattern(path) {
155
+ return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "**:$1").replace(/\{([^}]+)\}/g, ":$1");
156
+ }
157
+ function decodeParams(params) {
158
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
159
+ }
160
+
161
+ export {
162
+ OpenAPICodec,
163
+ OpenAPIMatcher
164
+ };
165
+ //# sourceMappingURL=chunk-LPBZEW4B.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  OpenAPICodec,
3
3
  OpenAPIMatcher
4
- } from "./chunk-TOZPXKQC.js";
4
+ } from "./chunk-LPBZEW4B.js";
5
5
 
6
6
  // src/adapters/fetch/openapi-handler.ts
7
7
  import { toFetchResponse, toStandardRequest } from "@orpc/server-standard-fetch";
@@ -29,4 +29,4 @@ var OpenAPIHandler = class {
29
29
  export {
30
30
  OpenAPIHandler
31
31
  };
32
- //# sourceMappingURL=chunk-5QMOOQSF.js.map
32
+ //# sourceMappingURL=chunk-UU2TTVB2.js.map
@@ -0,0 +1,13 @@
1
+ // src/utils.ts
2
+ function standardizeHTTPPath(path) {
3
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
4
+ }
5
+ function toOpenAPI31RoutePattern(path) {
6
+ return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "{$1}");
7
+ }
8
+
9
+ export {
10
+ standardizeHTTPPath,
11
+ toOpenAPI31RoutePattern
12
+ };
13
+ //# sourceMappingURL=chunk-XGHV4TH3.js.map
package/dist/fetch.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-5QMOOQSF.js";
4
- import "./chunk-TOZPXKQC.js";
5
- import "./chunk-HC5PVG4R.js";
3
+ } from "./chunk-UU2TTVB2.js";
4
+ import "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/hono.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-5QMOOQSF.js";
4
- import "./chunk-TOZPXKQC.js";
5
- import "./chunk-HC5PVG4R.js";
3
+ } from "./chunk-UU2TTVB2.js";
4
+ import "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
- JSONSerializer,
3
- standardizeHTTPPath
4
- } from "./chunk-HC5PVG4R.js";
2
+ standardizeHTTPPath,
3
+ toOpenAPI31RoutePattern
4
+ } from "./chunk-XGHV4TH3.js";
5
5
 
6
6
  // src/openapi-operation-extender.ts
7
7
  import { isProcedure } from "@orpc/server";
@@ -80,7 +80,9 @@ var OpenAPIContentBuilder = class {
80
80
  };
81
81
 
82
82
  // src/openapi-generator.ts
83
- import { fallbackContractConfig as fallbackContractConfig2, fallbackORPCErrorStatus, getEventIteratorSchemaDetails } from "@orpc/contract";
83
+ import { fallbackORPCErrorStatus } from "@orpc/client";
84
+ import { OpenAPIJsonSerializer } from "@orpc/client/openapi";
85
+ import { fallbackContractConfig as fallbackContractConfig2, getEventIteratorSchemaDetails } from "@orpc/contract";
84
86
  import { eachAllContractProcedure } from "@orpc/server";
85
87
  import { group } from "@orpc/shared";
86
88
 
@@ -333,10 +335,10 @@ var NON_LOGIC_KEYWORDS = [
333
335
  // src/schema-utils.ts
334
336
  var SchemaUtils = class {
335
337
  isFileSchema(schema) {
336
- return typeof schema === "object" && schema.type === "string" && typeof schema.contentMediaType === "string";
338
+ return isObject2(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
337
339
  }
338
340
  isObjectSchema(schema) {
339
- return typeof schema === "object" && schema.type === "object";
341
+ return isObject2(schema) && schema.type === "object";
340
342
  }
341
343
  isAnySchema(schema) {
342
344
  return schema === true || Object.keys(schema).filter((key) => !NON_LOGIC_KEYWORDS.includes(key)).length === 0;
@@ -435,7 +437,7 @@ var OpenAPIGenerator = class {
435
437
  this.parametersBuilder = options?.parametersBuilder ?? new OpenAPIParametersBuilder();
436
438
  this.schemaConverter = new CompositeSchemaConverter(options?.schemaConverters ?? []);
437
439
  this.schemaUtils = options?.schemaUtils ?? new SchemaUtils();
438
- this.jsonSerializer = options?.jsonSerializer ?? new JSONSerializer();
440
+ this.jsonSerializer = options?.jsonSerializer ?? new OpenAPIJsonSerializer();
439
441
  this.contentBuilder = options?.contentBuilder ?? new OpenAPIContentBuilder(this.schemaUtils);
440
442
  this.pathParser = new OpenAPIPathParser();
441
443
  this.inputStructureParser = options?.inputStructureParser ?? new OpenAPIInputStructureParser(this.schemaConverter, this.schemaUtils, this.pathParser);
@@ -461,7 +463,7 @@ var OpenAPIGenerator = class {
461
463
  return;
462
464
  }
463
465
  const method = fallbackContractConfig2("defaultMethod", def.route?.method);
464
- const httpPath = def.route?.path ? standardizeHTTPPath(def.route?.path) : `/${path.map(encodeURIComponent).join("/")}`;
466
+ const httpPath = def.route?.path ? toOpenAPI31RoutePattern(def.route?.path) : `/${path.map(encodeURIComponent).join("/")}`;
465
467
  const { parameters, requestBody } = (() => {
466
468
  const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(def.inputSchema);
467
469
  if (eventIteratorSchemaDetails) {
@@ -682,7 +684,6 @@ export {
682
684
  CompositeSchemaConverter,
683
685
  JSONSchema,
684
686
  Format as JSONSchemaFormat,
685
- JSONSerializer,
686
687
  NON_LOGIC_KEYWORDS,
687
688
  OpenAPIContentBuilder,
688
689
  OpenAPIGenerator,
@@ -694,6 +695,7 @@ export {
694
695
  getOperationExtender,
695
696
  oo,
696
697
  setOperationExtender,
697
- standardizeHTTPPath
698
+ standardizeHTTPPath,
699
+ toOpenAPI31RoutePattern
698
700
  };
699
701
  //# sourceMappingURL=index.js.map
package/dist/next.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-5QMOOQSF.js";
4
- import "./chunk-TOZPXKQC.js";
5
- import "./chunk-HC5PVG4R.js";
3
+ } from "./chunk-UU2TTVB2.js";
4
+ import "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/node.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPICodec,
3
3
  OpenAPIMatcher
4
- } from "./chunk-TOZPXKQC.js";
5
- import "./chunk-HC5PVG4R.js";
4
+ } from "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
 
7
7
  // src/adapters/node/openapi-handler.ts
8
8
  import { sendStandardResponse, toStandardRequest } from "@orpc/server-standard-node";
@@ -1,6 +1,4 @@
1
- export * as BracketNotation from './bracket-notation';
2
1
  export * from './openapi-codec';
3
2
  export * from './openapi-handler';
4
3
  export * from './openapi-matcher';
5
- export * from './openapi-serializer';
6
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,8 +1,8 @@
1
+ import type { ORPCError } from '@orpc/client';
1
2
  import type { AnyProcedure } from '@orpc/server';
2
3
  import type { StandardRequest, StandardResponse } from '@orpc/server-standard';
3
4
  import type { StandardCodec, StandardParams } from '@orpc/server/standard';
4
- import { type ORPCError } from '@orpc/contract';
5
- import { OpenAPISerializer } from './openapi-serializer';
5
+ import { OpenAPISerializer } from '@orpc/client/openapi';
6
6
  export interface OpenAPICodecOptions {
7
7
  serializer?: OpenAPISerializer;
8
8
  }
@@ -1,6 +1,5 @@
1
1
  /** unnoq */
2
2
  import { setOperationExtender } from './openapi-operation-extender';
3
- export * from './json-serializer';
4
3
  export * from './openapi';
5
4
  export * from './openapi-content-builder';
6
5
  export * from './openapi-generator';
@@ -2,9 +2,9 @@ import type { PublicOpenAPIInputStructureParser } from './openapi-input-structur
2
2
  import type { PublicOpenAPIOutputStructureParser } from './openapi-output-structure-parser';
3
3
  import type { PublicOpenAPIPathParser } from './openapi-path-parser';
4
4
  import type { SchemaConverter } from './schema-converter';
5
+ import { type PublicOpenAPIJsonSerializer } from '@orpc/client/openapi';
5
6
  import { type ContractRouter } from '@orpc/contract';
6
7
  import { type AnyRouter } from '@orpc/server';
7
- import { type PublicJSONSerializer } from './json-serializer';
8
8
  import { type OpenAPI } from './openapi';
9
9
  import { type PublicOpenAPIContentBuilder } from './openapi-content-builder';
10
10
  import { type PublicOpenAPIParametersBuilder } from './openapi-parameters-builder';
@@ -15,7 +15,7 @@ export interface OpenAPIGeneratorOptions {
15
15
  parametersBuilder?: PublicOpenAPIParametersBuilder;
16
16
  schemaConverters?: SchemaConverter[];
17
17
  schemaUtils?: PublicSchemaUtils;
18
- jsonSerializer?: PublicJSONSerializer;
18
+ jsonSerializer?: PublicOpenAPIJsonSerializer;
19
19
  pathParser?: PublicOpenAPIPathParser;
20
20
  inputStructureParser?: PublicOpenAPIInputStructureParser;
21
21
  outputStructureParser?: PublicOpenAPIOutputStructureParser;
@@ -1,3 +1,4 @@
1
1
  import type { HTTPPath } from '@orpc/contract';
2
2
  export declare function standardizeHTTPPath(path: HTTPPath): HTTPPath;
3
+ export declare function toOpenAPI31RoutePattern(path: HTTPPath): string;
3
4
  //# sourceMappingURL=utils.d.ts.map
package/dist/standard.js CHANGED
@@ -1,14 +1,10 @@
1
1
  import {
2
2
  OpenAPICodec,
3
- OpenAPIMatcher,
4
- OpenAPISerializer,
5
- bracket_notation_exports
6
- } from "./chunk-TOZPXKQC.js";
7
- import "./chunk-HC5PVG4R.js";
3
+ OpenAPIMatcher
4
+ } from "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
8
6
  export {
9
- bracket_notation_exports as BracketNotation,
10
7
  OpenAPICodec,
11
- OpenAPIMatcher,
12
- OpenAPISerializer
8
+ OpenAPIMatcher
13
9
  };
14
10
  //# sourceMappingURL=standard.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/openapi",
3
3
  "type": "module",
4
- "version": "0.40.0",
4
+ "version": "0.41.1",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -60,12 +60,12 @@
60
60
  "json-schema-typed": "^8.0.1",
61
61
  "openapi3-ts": "^4.4.0",
62
62
  "rou3": "^0.5.1",
63
- "@orpc/contract": "0.40.0",
64
- "@orpc/server": "0.40.0",
65
- "@orpc/shared": "0.40.0"
63
+ "@orpc/client": "0.41.1",
64
+ "@orpc/contract": "0.41.1",
65
+ "@orpc/server": "0.41.1",
66
+ "@orpc/shared": "0.41.1"
66
67
  },
67
68
  "devDependencies": {
68
- "@readme/openapi-parser": "^2.6.0",
69
69
  "zod": "^3.24.1"
70
70
  },
71
71
  "scripts": {
@@ -1,52 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/json-serializer.ts
8
- import { isObject } from "@orpc/shared";
9
- var JSONSerializer = class {
10
- serialize(payload) {
11
- if (payload instanceof Set)
12
- return this.serialize([...payload]);
13
- if (payload instanceof Map)
14
- return this.serialize([...payload.entries()]);
15
- if (Array.isArray(payload)) {
16
- return payload.map((v) => v === void 0 ? "undefined" : this.serialize(v));
17
- }
18
- if (Number.isNaN(payload))
19
- return "NaN";
20
- if (typeof payload === "bigint")
21
- return payload.toString();
22
- if (payload instanceof Date && Number.isNaN(payload.getTime())) {
23
- return "Invalid Date";
24
- }
25
- if (payload instanceof RegExp)
26
- return payload.toString();
27
- if (payload instanceof URL)
28
- return payload.toString();
29
- if (!isObject(payload))
30
- return payload;
31
- return Object.keys(payload).reduce(
32
- (carry, key) => {
33
- const val = payload[key];
34
- carry[key] = this.serialize(val);
35
- return carry;
36
- },
37
- {}
38
- );
39
- }
40
- };
41
-
42
- // src/utils.ts
43
- function standardizeHTTPPath(path) {
44
- return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
45
- }
46
-
47
- export {
48
- __export,
49
- JSONSerializer,
50
- standardizeHTTPPath
51
- };
52
- //# sourceMappingURL=chunk-HC5PVG4R.js.map
@@ -1,450 +0,0 @@
1
- import {
2
- JSONSerializer,
3
- __export,
4
- standardizeHTTPPath
5
- } from "./chunk-HC5PVG4R.js";
6
-
7
- // src/adapters/standard/bracket-notation.ts
8
- var bracket_notation_exports = {};
9
- __export(bracket_notation_exports, {
10
- deserialize: () => deserialize,
11
- escapeSegment: () => escapeSegment,
12
- parsePath: () => parsePath,
13
- serialize: () => serialize,
14
- stringifyPath: () => stringifyPath
15
- });
16
- import { isObject } from "@orpc/shared";
17
- function serialize(payload, parentKey = "") {
18
- if (!Array.isArray(payload) && !isObject(payload))
19
- return [["", payload]];
20
- const result = [];
21
- function helper(value, path) {
22
- if (Array.isArray(value)) {
23
- value.forEach((item, index) => {
24
- helper(item, [...path, String(index)]);
25
- });
26
- } else if (isObject(value)) {
27
- for (const [key, val] of Object.entries(value)) {
28
- helper(val, [...path, key]);
29
- }
30
- } else {
31
- result.push([stringifyPath(path), value]);
32
- }
33
- }
34
- helper(payload, parentKey ? [parentKey] : []);
35
- return result;
36
- }
37
- function deserialize(entities) {
38
- if (entities.length === 0) {
39
- return void 0;
40
- }
41
- const isRootArray = entities.every(([path]) => path === "");
42
- const result = isRootArray ? [] : {};
43
- const arrayPushPaths = /* @__PURE__ */ new Set();
44
- for (const [path, _] of entities) {
45
- const segments = parsePath(path);
46
- const base = segments.slice(0, -1).join(".");
47
- const last = segments[segments.length - 1];
48
- if (last === "") {
49
- arrayPushPaths.add(base);
50
- } else {
51
- arrayPushPaths.delete(base);
52
- }
53
- }
54
- function setValue(obj, segments, value, fullPath) {
55
- const [first, ...rest_] = segments;
56
- if (Array.isArray(obj) && first === "") {
57
- ;
58
- obj.push(value);
59
- return;
60
- }
61
- const objAsRecord = obj;
62
- if (rest_.length === 0) {
63
- objAsRecord[first] = value;
64
- return;
65
- }
66
- const rest = rest_;
67
- if (rest[0] === "") {
68
- const pathToCheck = segments.slice(0, -1).join(".");
69
- if (rest.length === 1 && arrayPushPaths.has(pathToCheck)) {
70
- if (!(first in objAsRecord)) {
71
- objAsRecord[first] = [];
72
- }
73
- if (Array.isArray(objAsRecord[first])) {
74
- ;
75
- objAsRecord[first].push(value);
76
- return;
77
- }
78
- }
79
- if (!(first in objAsRecord)) {
80
- objAsRecord[first] = {};
81
- }
82
- const target = objAsRecord[first];
83
- target[""] = value;
84
- return;
85
- }
86
- if (!(first in objAsRecord)) {
87
- objAsRecord[first] = {};
88
- }
89
- setValue(
90
- objAsRecord[first],
91
- rest,
92
- value,
93
- fullPath
94
- );
95
- }
96
- for (const [path, value] of entities) {
97
- const segments = parsePath(path);
98
- setValue(result, segments, value, path);
99
- }
100
- return result;
101
- }
102
- function escapeSegment(segment) {
103
- return segment.replace(/[\\[\]]/g, (match) => {
104
- switch (match) {
105
- case "\\":
106
- return "\\\\";
107
- case "[":
108
- return "\\[";
109
- case "]":
110
- return "\\]";
111
- default:
112
- return match;
113
- }
114
- });
115
- }
116
- function stringifyPath(path) {
117
- const [first, ...rest] = path;
118
- const firstSegment = escapeSegment(first);
119
- const base = first === "" ? "" : firstSegment;
120
- return rest.reduce(
121
- (result, segment) => `${result}[${escapeSegment(segment)}]`,
122
- base
123
- );
124
- }
125
- function parsePath(path) {
126
- if (path === "")
127
- return [""];
128
- const result = [];
129
- let currentSegment = "";
130
- let inBracket = false;
131
- let bracketContent = "";
132
- let backslashCount = 0;
133
- for (let i = 0; i < path.length; i++) {
134
- const char = path[i];
135
- if (char === "\\") {
136
- backslashCount++;
137
- continue;
138
- }
139
- if (backslashCount > 0) {
140
- const literalBackslashes = "\\".repeat(Math.floor(backslashCount / 2));
141
- if (char === "[" || char === "]") {
142
- if (backslashCount % 2 === 1) {
143
- if (inBracket) {
144
- bracketContent += literalBackslashes + char;
145
- } else {
146
- currentSegment += literalBackslashes + char;
147
- }
148
- } else {
149
- if (inBracket) {
150
- bracketContent += literalBackslashes;
151
- } else {
152
- currentSegment += literalBackslashes;
153
- }
154
- if (char === "[" && !inBracket) {
155
- if (currentSegment !== "" || result.length === 0) {
156
- result.push(currentSegment);
157
- }
158
- inBracket = true;
159
- bracketContent = "";
160
- currentSegment = "";
161
- } else if (char === "]" && inBracket) {
162
- result.push(bracketContent);
163
- inBracket = false;
164
- bracketContent = "";
165
- } else {
166
- if (inBracket) {
167
- bracketContent += char;
168
- } else {
169
- currentSegment += char;
170
- }
171
- }
172
- }
173
- } else {
174
- const allBackslashes = "\\".repeat(backslashCount);
175
- if (inBracket) {
176
- bracketContent += allBackslashes + char;
177
- } else {
178
- currentSegment += allBackslashes + char;
179
- }
180
- }
181
- backslashCount = 0;
182
- continue;
183
- }
184
- if (char === "[" && !inBracket) {
185
- if (currentSegment !== "" || result.length === 0) {
186
- result.push(currentSegment);
187
- }
188
- inBracket = true;
189
- bracketContent = "";
190
- currentSegment = "";
191
- continue;
192
- }
193
- if (char === "]" && inBracket) {
194
- result.push(bracketContent);
195
- inBracket = false;
196
- bracketContent = "";
197
- continue;
198
- }
199
- if (inBracket) {
200
- bracketContent += char;
201
- } else {
202
- currentSegment += char;
203
- }
204
- }
205
- if (backslashCount > 0) {
206
- const remainingBackslashes = "\\".repeat(backslashCount);
207
- if (inBracket) {
208
- bracketContent += remainingBackslashes;
209
- } else {
210
- currentSegment += remainingBackslashes;
211
- }
212
- }
213
- if (inBracket) {
214
- if (currentSegment !== "" || result.length === 0) {
215
- result.push(currentSegment);
216
- }
217
- result.push(`[${bracketContent}`);
218
- } else if (currentSegment !== "" || result.length === 0) {
219
- result.push(currentSegment);
220
- }
221
- return result;
222
- }
223
-
224
- // src/adapters/standard/openapi-codec.ts
225
- import { fallbackContractConfig } from "@orpc/contract";
226
- import { isObject as isObject2 } from "@orpc/shared";
227
-
228
- // src/adapters/standard/openapi-serializer.ts
229
- import { mapEventIterator, ORPCError, toORPCError } from "@orpc/contract";
230
- import { ErrorEvent, isAsyncIteratorObject } from "@orpc/server-standard";
231
- import { findDeepMatches } from "@orpc/shared";
232
- var OpenAPISerializer = class {
233
- jsonSerializer;
234
- constructor(options) {
235
- this.jsonSerializer = options?.jsonSerializer ?? new JSONSerializer();
236
- }
237
- serialize(data) {
238
- if (data instanceof Blob || data === void 0) {
239
- return data;
240
- }
241
- if (isAsyncIteratorObject(data)) {
242
- return mapEventIterator(data, {
243
- value: async (value) => this.jsonSerializer.serialize(value),
244
- error: async (e) => {
245
- if (e instanceof ErrorEvent) {
246
- return new ErrorEvent({
247
- data: this.jsonSerializer.serialize(e.data),
248
- cause: e
249
- });
250
- }
251
- return new ErrorEvent({
252
- data: this.jsonSerializer.serialize(toORPCError(e).toJSON()),
253
- cause: e
254
- });
255
- }
256
- });
257
- }
258
- const serializedJSON = this.jsonSerializer.serialize(data);
259
- const { values: blobs } = findDeepMatches((v) => v instanceof Blob, serializedJSON);
260
- if (blobs.length === 0) {
261
- return serializedJSON;
262
- }
263
- const form = new FormData();
264
- for (const [path, value] of serialize(serializedJSON)) {
265
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
266
- form.append(path, value.toString());
267
- } else if (value instanceof Date) {
268
- form.append(path, value.toISOString());
269
- } else if (value instanceof Blob) {
270
- form.append(path, value);
271
- }
272
- }
273
- return form;
274
- }
275
- deserialize(serialized) {
276
- if (serialized instanceof URLSearchParams || serialized instanceof FormData) {
277
- return deserialize([...serialized.entries()]);
278
- }
279
- if (isAsyncIteratorObject(serialized)) {
280
- return mapEventIterator(serialized, {
281
- value: async (value) => value,
282
- error: async (e) => {
283
- if (e instanceof ErrorEvent && ORPCError.isValidJSON(e.data)) {
284
- return ORPCError.fromJSON(e.data, { cause: e });
285
- }
286
- return e;
287
- }
288
- });
289
- }
290
- return serialized;
291
- }
292
- };
293
-
294
- // src/adapters/standard/openapi-codec.ts
295
- var OpenAPICodec = class {
296
- serializer;
297
- constructor(options) {
298
- this.serializer = options?.serializer ?? new OpenAPISerializer();
299
- }
300
- async decode(request, params, procedure) {
301
- const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
302
- if (inputStructure === "compact") {
303
- const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
304
- if (data === void 0) {
305
- return params;
306
- }
307
- if (isObject2(data)) {
308
- return {
309
- ...params,
310
- ...data
311
- };
312
- }
313
- return data;
314
- }
315
- const deserializeSearchParams = () => {
316
- return this.serializer.deserialize(request.url.searchParams);
317
- };
318
- return {
319
- params,
320
- get query() {
321
- const value = deserializeSearchParams();
322
- Object.defineProperty(this, "query", { value, writable: true });
323
- return value;
324
- },
325
- set query(value) {
326
- Object.defineProperty(this, "query", { value, writable: true });
327
- },
328
- headers: request.headers,
329
- body: this.serializer.deserialize(await request.body())
330
- };
331
- }
332
- encode(output, procedure) {
333
- const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
334
- const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
335
- if (outputStructure === "compact") {
336
- return {
337
- status: successStatus,
338
- headers: {},
339
- body: this.serializer.serialize(output)
340
- };
341
- }
342
- if (!isObject2(output)) {
343
- throw new Error(
344
- 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
345
- );
346
- }
347
- return {
348
- status: successStatus,
349
- headers: output.headers ?? {},
350
- body: this.serializer.serialize(output.body)
351
- };
352
- }
353
- encodeError(error) {
354
- return {
355
- status: error.status,
356
- headers: {},
357
- body: this.serializer.serialize(error.toJSON())
358
- };
359
- }
360
- };
361
-
362
- // src/adapters/standard/openapi-matcher.ts
363
- import { fallbackContractConfig as fallbackContractConfig2 } from "@orpc/contract";
364
- import { convertPathToHttpPath, createContractedProcedure, eachContractProcedure, getLazyRouterPrefix, getRouterChild, isProcedure, unlazy } from "@orpc/server";
365
- import { addRoute, createRouter, findRoute } from "rou3";
366
- var OpenAPIMatcher = class {
367
- tree = createRouter();
368
- ignoreUndefinedMethod;
369
- constructor(options) {
370
- this.ignoreUndefinedMethod = options?.ignoreUndefinedMethod ?? false;
371
- }
372
- pendingRouters = [];
373
- init(router, path = []) {
374
- const laziedOptions = eachContractProcedure({
375
- router,
376
- path
377
- }, ({ path: path2, contract }) => {
378
- if (!contract["~orpc"].route.method && this.ignoreUndefinedMethod) {
379
- return;
380
- }
381
- const method = fallbackContractConfig2("defaultMethod", contract["~orpc"].route.method);
382
- const httpPath = contract["~orpc"].route.path ? convertOpenAPIPathToRouterPath(contract["~orpc"].route.path) : convertPathToHttpPath(path2);
383
- if (isProcedure(contract)) {
384
- addRoute(this.tree, method, httpPath, {
385
- path: path2,
386
- contract,
387
- procedure: contract,
388
- // this mean dev not used contract-first so we can used contract as procedure directly
389
- router
390
- });
391
- } else {
392
- addRoute(this.tree, method, httpPath, {
393
- path: path2,
394
- contract,
395
- procedure: void 0,
396
- router
397
- });
398
- }
399
- });
400
- this.pendingRouters.push(...laziedOptions.map((option) => ({
401
- ...option,
402
- httpPathPrefix: convertPathToHttpPath(option.path),
403
- laziedPrefix: getLazyRouterPrefix(option.lazied)
404
- })));
405
- }
406
- async match(method, pathname) {
407
- if (this.pendingRouters.length) {
408
- const newPendingRouters = [];
409
- for (const pendingRouter of this.pendingRouters) {
410
- if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
411
- const { default: router } = await unlazy(pendingRouter.lazied);
412
- this.init(router, pendingRouter.path);
413
- } else {
414
- newPendingRouters.push(pendingRouter);
415
- }
416
- }
417
- this.pendingRouters = newPendingRouters;
418
- }
419
- const match = findRoute(this.tree, method, pathname);
420
- if (!match) {
421
- return void 0;
422
- }
423
- if (!match.data.procedure) {
424
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.data.router, ...match.data.path));
425
- if (!isProcedure(maybeProcedure)) {
426
- throw new Error(`
427
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.data.path)}.
428
- Ensure that the procedure is correctly defined and matches the expected contract.
429
- `);
430
- }
431
- match.data.procedure = createContractedProcedure(match.data.contract, maybeProcedure);
432
- }
433
- return {
434
- path: match.data.path,
435
- procedure: match.data.procedure,
436
- params: match.params
437
- };
438
- }
439
- };
440
- function convertOpenAPIPathToRouterPath(path) {
441
- return standardizeHTTPPath(path).replace(/\{([^}]+)\}/g, ":$1");
442
- }
443
-
444
- export {
445
- bracket_notation_exports,
446
- OpenAPISerializer,
447
- OpenAPICodec,
448
- OpenAPIMatcher
449
- };
450
- //# sourceMappingURL=chunk-TOZPXKQC.js.map
@@ -1,84 +0,0 @@
1
- /**
2
- * Serialize an object or array into a list of [key, value] pairs.
3
- * The key will express by using bracket-notation.
4
- *
5
- * Notice: This way cannot express the empty object or array.
6
- *
7
- * @example
8
- * ```ts
9
- * const payload = {
10
- * name: 'John Doe',
11
- * pets: ['dog', 'cat'],
12
- * }
13
- *
14
- * const entities = serialize(payload)
15
- *
16
- * expect(entities).toEqual([
17
- * ['name', 'John Doe'],
18
- * ['name[pets][0]', 'dog'],
19
- * ['name[pets][1]', 'cat'],
20
- * ])
21
- * ```
22
- */
23
- export declare function serialize(payload: unknown, parentKey?: string): [string, unknown][];
24
- /**
25
- * Deserialize a list of [key, value] pairs into an object or array.
26
- * The key is expressed by using bracket-notation.
27
- *
28
- * @example
29
- * ```ts
30
- * const entities = [
31
- * ['name', 'John Doe'],
32
- * ['name[pets][0]', 'dog'],
33
- * ['name[pets][1]', 'cat'],
34
- * ['name[dogs][]', 'hello'],
35
- * ['name[dogs][]', 'kitty'],
36
- * ]
37
- *
38
- * const payload = deserialize(entities)
39
- *
40
- * expect(payload).toEqual({
41
- * name: 'John Doe',
42
- * pets: { 0: 'dog', 1: 'cat' },
43
- * dogs: ['hello', 'kitty'],
44
- * })
45
- * ```
46
- */
47
- export declare function deserialize(entities: readonly (readonly [string, unknown])[]): Record<string, unknown> | unknown[] | undefined;
48
- /**
49
- * Escape the `[`, `]`, and `\` chars in a path segment.
50
- *
51
- * @example
52
- * ```ts
53
- * expect(escapeSegment('name[pets')).toEqual('name\\[pets')
54
- * ```
55
- */
56
- export declare function escapeSegment(segment: string): string;
57
- /**
58
- * Convert an array of path segments into a path string using bracket-notation.
59
- *
60
- * For the special char `[`, `]`, and `\` will be escaped by adding `\` at start.
61
- *
62
- * @example
63
- * ```ts
64
- * expect(stringifyPath(['name', 'pets', '0'])).toEqual('name[pets][0]')
65
- * ```
66
- */
67
- export declare function stringifyPath(path: readonly [string, ...string[]]): string;
68
- /**
69
- * Convert a path string using bracket-notation into an array of path segments.
70
- *
71
- * For the special char `[`, `]`, and `\` you should escape by adding `\` at start.
72
- * It only treats a pair `[${string}]` as a path segment.
73
- * If missing or escape it will bypass and treat as normal string.
74
- *
75
- * @example
76
- * ```ts
77
- * expect(parsePath('name[pets][0]')).toEqual(['name', 'pets', '0'])
78
- * expect(parsePath('name[pets][0')).toEqual(['name', 'pets', '[0'])
79
- * expect(parsePath('name[pets[0]')).toEqual(['name', 'pets[0')
80
- * expect(parsePath('name\\[pets][0]')).toEqual(['name[pets]', '0'])
81
- * ```
82
- */
83
- export declare function parsePath(path: string): [string, ...string[]];
84
- //# sourceMappingURL=bracket-notation.d.ts.map
@@ -1,11 +0,0 @@
1
- import type { PublicJSONSerializer } from '../../json-serializer';
2
- export interface OpenAPISerializerOptions {
3
- jsonSerializer?: PublicJSONSerializer;
4
- }
5
- export declare class OpenAPISerializer {
6
- private readonly jsonSerializer;
7
- constructor(options?: OpenAPISerializerOptions);
8
- serialize(data: unknown): unknown;
9
- deserialize(serialized: unknown): unknown;
10
- }
11
- //# sourceMappingURL=openapi-serializer.d.ts.map
@@ -1,5 +0,0 @@
1
- export declare class JSONSerializer {
2
- serialize(payload: unknown): unknown;
3
- }
4
- export type PublicJSONSerializer = Pick<JSONSerializer, keyof JSONSerializer>;
5
- //# sourceMappingURL=json-serializer.d.ts.map