@counterfact/client 0.1.0 → 0.2.0
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/CHANGELOG.md +20 -0
- package/README.md +13 -3
- package/dist/index.d.ts +1 -1
- package/dist/raw-http-client.js +19 -2
- package/dist/route-builder.d.ts +33 -3
- package/dist/route-builder.js +304 -14
- package/dist/route-catalog.d.ts +13 -0
- package/dist/route-catalog.js +28 -1
- package/package.json +2 -2
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# @counterfact/client
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 13155b0: Display complete multipart request bodies in the REPL client output, and write
|
|
8
|
+
route help directly to the console.
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- 04d67bb: Validate and send required OpenAPI cookie, body, and form inputs through the immutable route builder, including REPL completions for the new methods.
|
|
13
|
+
|
|
14
|
+
## 0.1.1
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- 5e59b84: Match required request header names case-insensitively.
|
|
19
|
+
- 28aafab: Percent-encode path parameter values before sending requests.
|
|
20
|
+
- 28aafab: Include inherited path-item parameters in route request guidance and validation.
|
package/README.md
CHANGED
|
@@ -34,13 +34,23 @@ const route = createRouteFunction(3000, "localhost", catalog);
|
|
|
34
34
|
const pet = route("/pets/{petId}").method("get").path({ petId: 42 });
|
|
35
35
|
|
|
36
36
|
console.log(pet.ready());
|
|
37
|
-
|
|
37
|
+
pet.help();
|
|
38
38
|
await pet.send();
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
Builder methods are immutable: calling `path()`, `query()`, `headers()`,
|
|
42
|
-
`body()`, or `method()` returns a new builder, so a
|
|
43
|
-
safely branched into reusable variants.
|
|
42
|
+
`cookies()`, `body()`, `form()`, or `method()` returns a new builder, so a
|
|
43
|
+
common request can be safely branched into reusable variants.
|
|
44
|
+
|
|
45
|
+
The builder validates required OpenAPI path, query, header, cookie, body, and
|
|
46
|
+
form inputs. Use `cookies()` to merge percent-encoded cookie pairs with an
|
|
47
|
+
existing `Cookie` header. Use `form()` for OpenAPI form content; it sends
|
|
48
|
+
URL-encoded data by default and text-only multipart data when
|
|
49
|
+
`multipart/form-data` is the sole declared form type. Binary and file form
|
|
50
|
+
parts are not supported.
|
|
51
|
+
|
|
52
|
+
Only one request entity is active. Calling `body()` after `form()`, or `form()`
|
|
53
|
+
after `body()`, clears the earlier entity so the last method wins.
|
|
44
54
|
|
|
45
55
|
See [`examples/reusable-request.mjs`](./examples/reusable-request.mjs) for a
|
|
46
56
|
complete example with a local HTTP server.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { RawHttpClient } from "./raw-http-client.js";
|
|
2
2
|
export { RouteBuilder, createRouteFunction, type MissingParam, type MissingParams, type RouteBuilderOptions, type RouteParams, } from "./route-builder.js";
|
|
3
|
-
export { createOpenApiRouteCatalog, type OpenApiRouteDocument, type RouteCatalog, type RouteOperation, type RouteParameter, } from "./route-catalog.js";
|
|
3
|
+
export { createOpenApiRouteCatalog, type OpenApiRouteDocument, type RouteCatalog, type RouteOperation, type RouteParameter, type RouteRequestBody, } from "./route-catalog.js";
|
package/dist/raw-http-client.js
CHANGED
|
@@ -44,6 +44,23 @@ function highlightJson(text) {
|
|
|
44
44
|
return `${colors.yellow}${match}${colors.reset}`;
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Splits an HTTP message at its first head/body separator.
|
|
49
|
+
*
|
|
50
|
+
* Request and response bodies can themselves contain `\r\n\r\n`, notably in
|
|
51
|
+
* multipart form data, so splitting every occurrence would truncate the
|
|
52
|
+
* displayed body after its first part.
|
|
53
|
+
*/
|
|
54
|
+
function splitHttpMessage(raw) {
|
|
55
|
+
const separator = "\r\n\r\n";
|
|
56
|
+
const separatorIndex = raw.indexOf(separator);
|
|
57
|
+
if (separatorIndex === -1)
|
|
58
|
+
return [raw, ""];
|
|
59
|
+
return [
|
|
60
|
+
raw.slice(0, separatorIndex),
|
|
61
|
+
raw.slice(separatorIndex + separator.length),
|
|
62
|
+
];
|
|
63
|
+
}
|
|
47
64
|
function stringifyBody(body) {
|
|
48
65
|
if (typeof body === "string") {
|
|
49
66
|
return body;
|
|
@@ -147,7 +164,7 @@ export class RawHttpClient {
|
|
|
147
164
|
});
|
|
148
165
|
}
|
|
149
166
|
#printRequest(raw, requestNumber) {
|
|
150
|
-
const [head
|
|
167
|
+
const [head, body] = splitHttpMessage(raw);
|
|
151
168
|
const lines = head.split("\r\n");
|
|
152
169
|
process.stdout.write(`${colors.cyan}\n----- REQUEST #${requestNumber} -----${colors.reset}\n`);
|
|
153
170
|
process.stdout.write(`${colors.cyan}${lines[0]}${colors.reset}\n`);
|
|
@@ -163,7 +180,7 @@ export class RawHttpClient {
|
|
|
163
180
|
}
|
|
164
181
|
}
|
|
165
182
|
#printResponse(raw, requestNumber) {
|
|
166
|
-
const [head
|
|
183
|
+
const [head, body] = splitHttpMessage(raw);
|
|
167
184
|
const lines = head.split("\r\n");
|
|
168
185
|
const statusLine = lines[0] ?? "";
|
|
169
186
|
let statusColor = colors.green;
|
package/dist/route-builder.d.ts
CHANGED
|
@@ -6,12 +6,17 @@ export interface MissingParam {
|
|
|
6
6
|
type?: string;
|
|
7
7
|
}
|
|
8
8
|
export interface MissingParams {
|
|
9
|
+
body?: MissingParam[];
|
|
10
|
+
cookie?: MissingParam[];
|
|
11
|
+
formData?: MissingParam[];
|
|
9
12
|
header?: MissingParam[];
|
|
10
13
|
path?: MissingParam[];
|
|
11
14
|
query?: MissingParam[];
|
|
12
15
|
}
|
|
13
16
|
export interface RouteBuilderOptions {
|
|
14
17
|
body?: unknown;
|
|
18
|
+
cookieParams?: RouteParams;
|
|
19
|
+
formParams?: RouteParams;
|
|
15
20
|
headerParams?: RouteParams;
|
|
16
21
|
host?: string;
|
|
17
22
|
method?: string;
|
|
@@ -36,6 +41,10 @@ export interface RouteBuilderOptions {
|
|
|
36
41
|
export declare class RouteBuilder {
|
|
37
42
|
readonly routePath: string;
|
|
38
43
|
private readonly _body;
|
|
44
|
+
private readonly _bodySet;
|
|
45
|
+
private readonly _cookieParams;
|
|
46
|
+
private readonly _formParams;
|
|
47
|
+
private readonly _formSet;
|
|
39
48
|
private readonly _headerParams;
|
|
40
49
|
private readonly _host;
|
|
41
50
|
private readonly _method;
|
|
@@ -71,13 +80,34 @@ export declare class RouteBuilder {
|
|
|
71
80
|
* @param params - Key/value map of header names to values.
|
|
72
81
|
*/
|
|
73
82
|
headers(params: RouteParams): RouteBuilder;
|
|
83
|
+
/**
|
|
84
|
+
* Returns a new builder with additional request cookies merged in.
|
|
85
|
+
*
|
|
86
|
+
* Cookie names and values are percent-encoded when the request is sent.
|
|
87
|
+
*
|
|
88
|
+
* @param params - Key/value map of cookie names to values.
|
|
89
|
+
*/
|
|
90
|
+
cookies(params: RouteParams): RouteBuilder;
|
|
74
91
|
/**
|
|
75
92
|
* Returns a new builder with the request body set.
|
|
76
93
|
*
|
|
77
94
|
* @param body - The request body (will be serialised to JSON or sent as-is).
|
|
78
95
|
*/
|
|
79
96
|
body(body: unknown): RouteBuilder;
|
|
97
|
+
/**
|
|
98
|
+
* Returns a new builder with additional text form fields merged in.
|
|
99
|
+
*
|
|
100
|
+
* Calling `form()` after `body()` clears the body. Calling `body()` after
|
|
101
|
+
* `form()` clears the form, so the last entity method wins.
|
|
102
|
+
*
|
|
103
|
+
* @param params - Key/value map of form field names to text values.
|
|
104
|
+
*/
|
|
105
|
+
form(params: RouteParams): RouteBuilder;
|
|
80
106
|
private getOperation;
|
|
107
|
+
private getHeaderValue;
|
|
108
|
+
private getHeaderCookies;
|
|
109
|
+
private getCookieValue;
|
|
110
|
+
private requestBodyIsSet;
|
|
81
111
|
/**
|
|
82
112
|
* Returns `true` when a method is set and no required parameters are
|
|
83
113
|
* missing.
|
|
@@ -86,14 +116,14 @@ export declare class RouteBuilder {
|
|
|
86
116
|
/**
|
|
87
117
|
* Returns a {@link MissingParams} object describing all required parameters
|
|
88
118
|
* that have not yet been set, or `undefined` when nothing is missing (or
|
|
89
|
-
* when the operation has no
|
|
119
|
+
* when the operation has no required inputs).
|
|
90
120
|
*/
|
|
91
121
|
missing(): MissingParams | undefined;
|
|
92
122
|
/**
|
|
93
|
-
*
|
|
123
|
+
* Writes human-readable help describing the operation, its
|
|
94
124
|
* parameters, and the expected responses.
|
|
95
125
|
*/
|
|
96
|
-
help():
|
|
126
|
+
help(): void;
|
|
97
127
|
/**
|
|
98
128
|
* Executes the HTTP request and returns the parsed response body.
|
|
99
129
|
*
|
package/dist/route-builder.js
CHANGED
|
@@ -1,4 +1,54 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
1
2
|
import { RawHttpClient } from "./raw-http-client.js";
|
|
3
|
+
const FORM_URLENCODED = "application/x-www-form-urlencoded";
|
|
4
|
+
const FORM_MULTIPART = "multipart/form-data";
|
|
5
|
+
function isFormContentType(contentType) {
|
|
6
|
+
const normalized = contentType.toLowerCase();
|
|
7
|
+
return normalized === FORM_URLENCODED || normalized === FORM_MULTIPART;
|
|
8
|
+
}
|
|
9
|
+
function getRequestBodyContentTypes(operation) {
|
|
10
|
+
return Object.keys(operation.requestBody?.content ?? {});
|
|
11
|
+
}
|
|
12
|
+
function getFormContentType(operation) {
|
|
13
|
+
if (!operation)
|
|
14
|
+
return FORM_URLENCODED;
|
|
15
|
+
const declared = [
|
|
16
|
+
...(operation.consumes ?? []),
|
|
17
|
+
...getRequestBodyContentTypes(operation),
|
|
18
|
+
].map((contentType) => contentType.toLowerCase());
|
|
19
|
+
if (declared.includes(FORM_URLENCODED))
|
|
20
|
+
return FORM_URLENCODED;
|
|
21
|
+
if (declared.includes(FORM_MULTIPART))
|
|
22
|
+
return FORM_MULTIPART;
|
|
23
|
+
return FORM_URLENCODED;
|
|
24
|
+
}
|
|
25
|
+
function findHeaderKey(headers, target) {
|
|
26
|
+
const normalizedTarget = target.toLowerCase();
|
|
27
|
+
return Object.keys(headers).find((name) => name.toLowerCase() === normalizedTarget);
|
|
28
|
+
}
|
|
29
|
+
function setHeader(headers, name, value) {
|
|
30
|
+
const existing = Object.keys(headers).find((headerName) => headerName.toLowerCase() === name.toLowerCase());
|
|
31
|
+
headers[existing ?? name] = value;
|
|
32
|
+
}
|
|
33
|
+
function decodeCookieName(name) {
|
|
34
|
+
try {
|
|
35
|
+
return decodeURIComponent(name);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return name;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function escapeMultipartName(name) {
|
|
42
|
+
return name
|
|
43
|
+
.replaceAll("\\", "\\\\")
|
|
44
|
+
.replaceAll('"', '\\"')
|
|
45
|
+
.replaceAll("\r", "%0D")
|
|
46
|
+
.replaceAll("\n", "%0A");
|
|
47
|
+
}
|
|
48
|
+
function encodeMultipartForm(params, boundary) {
|
|
49
|
+
const parts = Object.entries(params).map(([name, value]) => `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartName(name)}"\r\n\r\n${String(value)}\r\n`);
|
|
50
|
+
return `${parts.join("")}--${boundary}--\r\n`;
|
|
51
|
+
}
|
|
2
52
|
/**
|
|
3
53
|
* Immutable fluent builder for constructing and sending HTTP requests from the
|
|
4
54
|
* Counterfact REPL.
|
|
@@ -15,6 +65,10 @@ import { RawHttpClient } from "./raw-http-client.js";
|
|
|
15
65
|
export class RouteBuilder {
|
|
16
66
|
routePath;
|
|
17
67
|
_body;
|
|
68
|
+
_bodySet;
|
|
69
|
+
_cookieParams;
|
|
70
|
+
_formParams;
|
|
71
|
+
_formSet;
|
|
18
72
|
_headerParams;
|
|
19
73
|
_host;
|
|
20
74
|
_method;
|
|
@@ -29,7 +83,11 @@ export class RouteBuilder {
|
|
|
29
83
|
this._pathParams = options.pathParams ?? {};
|
|
30
84
|
this._queryParams = options.queryParams ?? {};
|
|
31
85
|
this._headerParams = options.headerParams ?? {};
|
|
86
|
+
this._cookieParams = options.cookieParams ?? {};
|
|
32
87
|
this._body = options.body;
|
|
88
|
+
this._formParams = options.formParams ?? {};
|
|
89
|
+
this._formSet = "formParams" in options;
|
|
90
|
+
this._bodySet = options.body !== undefined && !this._formSet;
|
|
33
91
|
this._port = options.port;
|
|
34
92
|
this._host = options.host ?? "localhost";
|
|
35
93
|
this._routeCatalog = options.routeCatalog;
|
|
@@ -41,8 +99,8 @@ export class RouteBuilder {
|
|
|
41
99
|
return this._routeCatalog.getOperation(this.routePath, this._method);
|
|
42
100
|
}
|
|
43
101
|
clone(overrides) {
|
|
44
|
-
|
|
45
|
-
|
|
102
|
+
const options = {
|
|
103
|
+
cookieParams: overrides.cookieParams ?? this._cookieParams,
|
|
46
104
|
headerParams: overrides.headerParams ?? this._headerParams,
|
|
47
105
|
host: this._host,
|
|
48
106
|
method: overrides.method ?? this._method,
|
|
@@ -50,7 +108,20 @@ export class RouteBuilder {
|
|
|
50
108
|
port: this._port,
|
|
51
109
|
queryParams: overrides.queryParams ?? this._queryParams,
|
|
52
110
|
routeCatalog: this._routeCatalog,
|
|
53
|
-
}
|
|
111
|
+
};
|
|
112
|
+
if ("formParams" in overrides) {
|
|
113
|
+
options.formParams = overrides.formParams;
|
|
114
|
+
}
|
|
115
|
+
else if ("body" in overrides) {
|
|
116
|
+
options.body = overrides.body;
|
|
117
|
+
}
|
|
118
|
+
else if (this._formSet) {
|
|
119
|
+
options.formParams = this._formParams;
|
|
120
|
+
}
|
|
121
|
+
else if (this._bodySet) {
|
|
122
|
+
options.body = this._body;
|
|
123
|
+
}
|
|
124
|
+
return new RouteBuilder(this.routePath, options);
|
|
54
125
|
}
|
|
55
126
|
/**
|
|
56
127
|
* Returns a new builder with the HTTP method set.
|
|
@@ -84,6 +155,16 @@ export class RouteBuilder {
|
|
|
84
155
|
headers(params) {
|
|
85
156
|
return this.clone({ headerParams: { ...this._headerParams, ...params } });
|
|
86
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Returns a new builder with additional request cookies merged in.
|
|
160
|
+
*
|
|
161
|
+
* Cookie names and values are percent-encoded when the request is sent.
|
|
162
|
+
*
|
|
163
|
+
* @param params - Key/value map of cookie names to values.
|
|
164
|
+
*/
|
|
165
|
+
cookies(params) {
|
|
166
|
+
return this.clone({ cookieParams: { ...this._cookieParams, ...params } });
|
|
167
|
+
}
|
|
87
168
|
/**
|
|
88
169
|
* Returns a new builder with the request body set.
|
|
89
170
|
*
|
|
@@ -92,9 +173,56 @@ export class RouteBuilder {
|
|
|
92
173
|
body(body) {
|
|
93
174
|
return this.clone({ body });
|
|
94
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Returns a new builder with additional text form fields merged in.
|
|
178
|
+
*
|
|
179
|
+
* Calling `form()` after `body()` clears the body. Calling `body()` after
|
|
180
|
+
* `form()` clears the form, so the last entity method wins.
|
|
181
|
+
*
|
|
182
|
+
* @param params - Key/value map of form field names to text values.
|
|
183
|
+
*/
|
|
184
|
+
form(params) {
|
|
185
|
+
const current = this._formSet ? this._formParams : {};
|
|
186
|
+
return this.clone({ formParams: { ...current, ...params } });
|
|
187
|
+
}
|
|
95
188
|
getOperation() {
|
|
96
189
|
return this._operation;
|
|
97
190
|
}
|
|
191
|
+
getHeaderValue(name) {
|
|
192
|
+
const key = findHeaderKey(this._headerParams, name);
|
|
193
|
+
return key === undefined ? undefined : this._headerParams[key];
|
|
194
|
+
}
|
|
195
|
+
getHeaderCookies() {
|
|
196
|
+
const cookieHeader = this.getHeaderValue("cookie");
|
|
197
|
+
const cookies = new Map();
|
|
198
|
+
if (cookieHeader === undefined)
|
|
199
|
+
return cookies;
|
|
200
|
+
for (const pair of String(cookieHeader).split(";")) {
|
|
201
|
+
const separator = pair.indexOf("=");
|
|
202
|
+
if (separator === -1)
|
|
203
|
+
continue;
|
|
204
|
+
const name = decodeCookieName(pair.slice(0, separator).trim());
|
|
205
|
+
const value = pair.slice(separator + 1).trim();
|
|
206
|
+
cookies.set(name, value);
|
|
207
|
+
}
|
|
208
|
+
return cookies;
|
|
209
|
+
}
|
|
210
|
+
getCookieValue(name) {
|
|
211
|
+
if (name in this._cookieParams)
|
|
212
|
+
return this._cookieParams[name];
|
|
213
|
+
return this.getHeaderCookies().get(name);
|
|
214
|
+
}
|
|
215
|
+
requestBodyIsSet(operation) {
|
|
216
|
+
const contentTypes = getRequestBodyContentTypes(operation);
|
|
217
|
+
if (this._formSet) {
|
|
218
|
+
return contentTypes.some(isFormContentType);
|
|
219
|
+
}
|
|
220
|
+
if (this._bodySet) {
|
|
221
|
+
return (contentTypes.length === 0 ||
|
|
222
|
+
contentTypes.some((contentType) => !isFormContentType(contentType)));
|
|
223
|
+
}
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
98
226
|
/**
|
|
99
227
|
* Returns `true` when a method is set and no required parameters are
|
|
100
228
|
* missing.
|
|
@@ -107,17 +235,19 @@ export class RouteBuilder {
|
|
|
107
235
|
/**
|
|
108
236
|
* Returns a {@link MissingParams} object describing all required parameters
|
|
109
237
|
* that have not yet been set, or `undefined` when nothing is missing (or
|
|
110
|
-
* when the operation has no
|
|
238
|
+
* when the operation has no required inputs).
|
|
111
239
|
*/
|
|
112
240
|
missing() {
|
|
113
241
|
const operation = this.getOperation();
|
|
114
|
-
if (!operation
|
|
242
|
+
if (!operation)
|
|
115
243
|
return undefined;
|
|
116
244
|
const missingParams = {};
|
|
117
|
-
for (const param of operation.parameters) {
|
|
245
|
+
for (const param of operation.parameters ?? []) {
|
|
118
246
|
if (!param.required)
|
|
119
247
|
continue;
|
|
120
|
-
const paramType = param.type ??
|
|
248
|
+
const paramType = param.type ??
|
|
249
|
+
param.schema?.type ??
|
|
250
|
+
(param.in === "body" ? "object" : "string");
|
|
121
251
|
const paramInfo = {
|
|
122
252
|
description: param.description,
|
|
123
253
|
name: param.name,
|
|
@@ -129,16 +259,40 @@ export class RouteBuilder {
|
|
|
129
259
|
else if (param.in === "query" && !(param.name in this._queryParams)) {
|
|
130
260
|
missingParams.query = [...(missingParams.query ?? []), paramInfo];
|
|
131
261
|
}
|
|
132
|
-
else if (param.in === "header" &&
|
|
262
|
+
else if (param.in === "header" &&
|
|
263
|
+
this.getHeaderValue(param.name) === undefined) {
|
|
133
264
|
missingParams.header = [...(missingParams.header ?? []), paramInfo];
|
|
134
265
|
}
|
|
266
|
+
else if (param.in === "cookie" &&
|
|
267
|
+
this.getCookieValue(param.name) === undefined) {
|
|
268
|
+
missingParams.cookie = [...(missingParams.cookie ?? []), paramInfo];
|
|
269
|
+
}
|
|
270
|
+
else if (param.in === "body" && !this._bodySet) {
|
|
271
|
+
missingParams.body = [...(missingParams.body ?? []), paramInfo];
|
|
272
|
+
}
|
|
273
|
+
else if (param.in === "formData" &&
|
|
274
|
+
(!this._formSet || !(param.name in this._formParams))) {
|
|
275
|
+
missingParams.formData = [...(missingParams.formData ?? []), paramInfo];
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (operation.requestBody?.required && !this.requestBodyIsSet(operation)) {
|
|
279
|
+
const schemas = Object.values(operation.requestBody.content ?? {});
|
|
280
|
+
missingParams.body = [
|
|
281
|
+
...(missingParams.body ?? []),
|
|
282
|
+
{
|
|
283
|
+
description: operation.requestBody.description,
|
|
284
|
+
name: "requestBody",
|
|
285
|
+
type: schemas.find((media) => media.schema?.type)?.schema?.type ??
|
|
286
|
+
"object",
|
|
287
|
+
},
|
|
288
|
+
];
|
|
135
289
|
}
|
|
136
290
|
if (Object.keys(missingParams).length === 0)
|
|
137
291
|
return undefined;
|
|
138
292
|
return missingParams;
|
|
139
293
|
}
|
|
140
294
|
/**
|
|
141
|
-
*
|
|
295
|
+
* Writes human-readable help describing the operation, its
|
|
142
296
|
* parameters, and the expected responses.
|
|
143
297
|
*/
|
|
144
298
|
help() {
|
|
@@ -160,6 +314,9 @@ export class RouteBuilder {
|
|
|
160
314
|
const pathParams = operation.parameters.filter((p) => p.in === "path");
|
|
161
315
|
const queryParams = operation.parameters.filter((p) => p.in === "query");
|
|
162
316
|
const headerParams = operation.parameters.filter((p) => p.in === "header");
|
|
317
|
+
const cookieParams = operation.parameters.filter((p) => p.in === "cookie");
|
|
318
|
+
const bodyParams = operation.parameters.filter((p) => p.in === "body");
|
|
319
|
+
const formParams = operation.parameters.filter((p) => p.in === "formData");
|
|
163
320
|
if (pathParams.length > 0) {
|
|
164
321
|
lines.push("");
|
|
165
322
|
lines.push("Path Parameters:");
|
|
@@ -198,6 +355,52 @@ export class RouteBuilder {
|
|
|
198
355
|
lines.push(` Description: ${p.description}`);
|
|
199
356
|
}
|
|
200
357
|
}
|
|
358
|
+
if (cookieParams.length > 0) {
|
|
359
|
+
lines.push("");
|
|
360
|
+
lines.push("Cookies:");
|
|
361
|
+
for (const p of cookieParams) {
|
|
362
|
+
const paramType = p.type ?? p.schema?.type ?? "string";
|
|
363
|
+
const required = p.required ? "required" : "optional";
|
|
364
|
+
lines.push(` ${p.name} (${paramType}, ${required})`);
|
|
365
|
+
if (p.description)
|
|
366
|
+
lines.push(` Description: ${p.description}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (formParams.length > 0) {
|
|
370
|
+
lines.push("");
|
|
371
|
+
lines.push("Form Fields:");
|
|
372
|
+
for (const p of formParams) {
|
|
373
|
+
const paramType = p.type ?? p.schema?.type ?? "string";
|
|
374
|
+
const required = p.required ? "required" : "optional";
|
|
375
|
+
lines.push(` ${p.name} (${paramType}, ${required})`);
|
|
376
|
+
if (p.description)
|
|
377
|
+
lines.push(` Description: ${p.description}`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (bodyParams.length > 0) {
|
|
381
|
+
lines.push("");
|
|
382
|
+
lines.push("Request Body:");
|
|
383
|
+
for (const p of bodyParams) {
|
|
384
|
+
const paramType = p.type ?? p.schema?.type ?? "object";
|
|
385
|
+
const required = p.required ? "required" : "optional";
|
|
386
|
+
lines.push(` ${p.name} (${paramType}, ${required})`);
|
|
387
|
+
if (p.description)
|
|
388
|
+
lines.push(` Description: ${p.description}`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (operation?.requestBody) {
|
|
393
|
+
const required = operation.requestBody.required ? "required" : "optional";
|
|
394
|
+
const contentTypes = getRequestBodyContentTypes(operation);
|
|
395
|
+
lines.push("");
|
|
396
|
+
lines.push("Request Body:");
|
|
397
|
+
lines.push(` requestBody (${required})`);
|
|
398
|
+
if (operation.requestBody.description) {
|
|
399
|
+
lines.push(` Description: ${operation.requestBody.description}`);
|
|
400
|
+
}
|
|
401
|
+
if (contentTypes.length > 0) {
|
|
402
|
+
lines.push(` Content types: ${contentTypes.join(" | ")}`);
|
|
403
|
+
}
|
|
201
404
|
}
|
|
202
405
|
if (operation?.responses) {
|
|
203
406
|
lines.push("");
|
|
@@ -209,7 +412,7 @@ export class RouteBuilder {
|
|
|
209
412
|
}
|
|
210
413
|
}
|
|
211
414
|
}
|
|
212
|
-
|
|
415
|
+
console.log(lines.join("\n"));
|
|
213
416
|
}
|
|
214
417
|
/**
|
|
215
418
|
* Executes the HTTP request and returns the parsed response body.
|
|
@@ -247,12 +450,30 @@ export class RouteBuilder {
|
|
|
247
450
|
lines.push(` - ${p.name} (${p.type ?? "string"})`);
|
|
248
451
|
}
|
|
249
452
|
}
|
|
453
|
+
if (missing.cookie) {
|
|
454
|
+
lines.push(" cookie:");
|
|
455
|
+
for (const p of missing.cookie) {
|
|
456
|
+
lines.push(` - ${p.name} (${p.type ?? "string"})`);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (missing.formData) {
|
|
460
|
+
lines.push(" formData:");
|
|
461
|
+
for (const p of missing.formData) {
|
|
462
|
+
lines.push(` - ${p.name} (${p.type ?? "string"})`);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (missing.body) {
|
|
466
|
+
lines.push(" body:");
|
|
467
|
+
for (const p of missing.body) {
|
|
468
|
+
lines.push(` - ${p.name} (${p.type ?? "object"})`);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
250
471
|
throw new Error(lines.join("\n"));
|
|
251
472
|
}
|
|
252
473
|
// Build URL with path parameters substituted
|
|
253
474
|
let url = this.routePath;
|
|
254
475
|
for (const [key, value] of Object.entries(this._pathParams)) {
|
|
255
|
-
url = url.replaceAll(`{${key}}`, String(value));
|
|
476
|
+
url = url.replaceAll(`{${key}}`, encodeURIComponent(String(value)));
|
|
256
477
|
}
|
|
257
478
|
// Append query string
|
|
258
479
|
const queryEntries = Object.entries(this._queryParams);
|
|
@@ -262,6 +483,29 @@ export class RouteBuilder {
|
|
|
262
483
|
}
|
|
263
484
|
const client = new RawHttpClient(this._host, this._port);
|
|
264
485
|
const headers = Object.fromEntries(Object.entries(this._headerParams).map(([k, v]) => [k, String(v)]));
|
|
486
|
+
const cookiePairs = Object.entries(this._cookieParams).map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`);
|
|
487
|
+
if (cookiePairs.length > 0) {
|
|
488
|
+
const cookieHeaderKey = Object.keys(headers).find((name) => name.toLowerCase() === "cookie");
|
|
489
|
+
let existingCookies;
|
|
490
|
+
if (cookieHeaderKey !== undefined) {
|
|
491
|
+
// eslint-disable-next-line security/detect-object-injection -- The key was selected from this inert header map.
|
|
492
|
+
existingCookies = headers[cookieHeaderKey];
|
|
493
|
+
}
|
|
494
|
+
setHeader(headers, "Cookie", [existingCookies, ...cookiePairs].filter(Boolean).join("; "));
|
|
495
|
+
}
|
|
496
|
+
let entity = this._body;
|
|
497
|
+
if (this._formSet) {
|
|
498
|
+
const formContentType = getFormContentType(this.getOperation());
|
|
499
|
+
if (formContentType === FORM_MULTIPART) {
|
|
500
|
+
const boundary = `counterfact-${randomBytes(16).toString("hex")}`;
|
|
501
|
+
entity = encodeMultipartForm(this._formParams, boundary);
|
|
502
|
+
setHeader(headers, "Content-Type", `${FORM_MULTIPART}; boundary=${boundary}`);
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
entity = new URLSearchParams(Object.entries(this._formParams).map(([name, value]) => [name, String(value)])).toString();
|
|
506
|
+
setHeader(headers, "Content-Type", FORM_URLENCODED);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
265
509
|
const method = this._method.toLowerCase();
|
|
266
510
|
switch (method) {
|
|
267
511
|
case "get":
|
|
@@ -275,11 +519,11 @@ export class RouteBuilder {
|
|
|
275
519
|
case "trace":
|
|
276
520
|
return client.trace(url, headers);
|
|
277
521
|
case "post":
|
|
278
|
-
return client.post(url,
|
|
522
|
+
return client.post(url, entity, headers);
|
|
279
523
|
case "put":
|
|
280
|
-
return client.put(url,
|
|
524
|
+
return client.put(url, entity, headers);
|
|
281
525
|
case "patch":
|
|
282
|
-
return client.patch(url,
|
|
526
|
+
return client.patch(url, entity, headers);
|
|
283
527
|
default:
|
|
284
528
|
throw new Error(`Unsupported HTTP method: ${this._method}`);
|
|
285
529
|
}
|
|
@@ -292,6 +536,10 @@ export class RouteBuilder {
|
|
|
292
536
|
if (operation?.parameters) {
|
|
293
537
|
const pathParams = operation.parameters.filter((p) => p.in === "path");
|
|
294
538
|
const queryParams = operation.parameters.filter((p) => p.in === "query");
|
|
539
|
+
const headerParams = operation.parameters.filter((p) => p.in === "header");
|
|
540
|
+
const cookieParams = operation.parameters.filter((p) => p.in === "cookie");
|
|
541
|
+
const formParams = operation.parameters.filter((p) => p.in === "formData");
|
|
542
|
+
const bodyParams = operation.parameters.filter((p) => p.in === "body");
|
|
295
543
|
if (pathParams.length > 0) {
|
|
296
544
|
lines.push("");
|
|
297
545
|
lines.push("Path:");
|
|
@@ -309,6 +557,48 @@ export class RouteBuilder {
|
|
|
309
557
|
lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
|
|
310
558
|
}
|
|
311
559
|
}
|
|
560
|
+
if (headerParams.length > 0) {
|
|
561
|
+
lines.push("");
|
|
562
|
+
lines.push("Headers:");
|
|
563
|
+
for (const p of headerParams) {
|
|
564
|
+
const value = this.getHeaderValue(p.name);
|
|
565
|
+
const label = p.required ? "[missing]" : "[optional]";
|
|
566
|
+
lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (cookieParams.length > 0) {
|
|
570
|
+
lines.push("");
|
|
571
|
+
lines.push("Cookies:");
|
|
572
|
+
for (const p of cookieParams) {
|
|
573
|
+
const value = this.getCookieValue(p.name);
|
|
574
|
+
const label = p.required ? "[missing]" : "[optional]";
|
|
575
|
+
lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (formParams.length > 0) {
|
|
579
|
+
lines.push("");
|
|
580
|
+
lines.push("Form:");
|
|
581
|
+
for (const p of formParams) {
|
|
582
|
+
const value = this._formSet ? this._formParams[p.name] : undefined;
|
|
583
|
+
const label = p.required ? "[missing]" : "[optional]";
|
|
584
|
+
lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (bodyParams.length > 0) {
|
|
588
|
+
lines.push("");
|
|
589
|
+
lines.push("Body:");
|
|
590
|
+
for (const p of bodyParams) {
|
|
591
|
+
const label = p.required ? "[missing]" : "[optional]";
|
|
592
|
+
lines.push(` ${p.name}: ${this._bodySet ? "[set]" : label}`);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
if (operation?.requestBody) {
|
|
597
|
+
const label = operation.requestBody.required ? "[missing]" : "[optional]";
|
|
598
|
+
const entityKind = this._formSet ? "form" : "body";
|
|
599
|
+
lines.push("");
|
|
600
|
+
lines.push("Body:");
|
|
601
|
+
lines.push(` requestBody: ${this.requestBodyIsSet(operation) ? `[set with ${entityKind}()]` : label}`);
|
|
312
602
|
}
|
|
313
603
|
lines.push("");
|
|
314
604
|
lines.push(`Ready: ${this.ready()}`);
|
package/dist/route-catalog.d.ts
CHANGED
|
@@ -11,10 +11,22 @@ export interface RouteParameter {
|
|
|
11
11
|
};
|
|
12
12
|
type?: string;
|
|
13
13
|
}
|
|
14
|
+
/** OpenAPI 3 request-body metadata consumed by request validation and help. */
|
|
15
|
+
export interface RouteRequestBody {
|
|
16
|
+
content?: Readonly<Record<string, {
|
|
17
|
+
schema?: {
|
|
18
|
+
type?: string;
|
|
19
|
+
};
|
|
20
|
+
}>>;
|
|
21
|
+
description?: string;
|
|
22
|
+
required?: boolean;
|
|
23
|
+
}
|
|
14
24
|
/** Operation metadata consumed by request help and validation. */
|
|
15
25
|
export interface RouteOperation {
|
|
26
|
+
consumes?: readonly string[];
|
|
16
27
|
description?: string;
|
|
17
28
|
parameters?: readonly RouteParameter[];
|
|
29
|
+
requestBody?: RouteRequestBody;
|
|
18
30
|
responses?: Readonly<Record<string, {
|
|
19
31
|
description?: string;
|
|
20
32
|
}>>;
|
|
@@ -30,6 +42,7 @@ export interface RouteCatalog {
|
|
|
30
42
|
}
|
|
31
43
|
/** The only OpenAPI document shape needed to create a route catalog. */
|
|
32
44
|
export interface OpenApiRouteDocument {
|
|
45
|
+
readonly consumes?: readonly string[];
|
|
33
46
|
readonly paths: Readonly<Record<string, object>>;
|
|
34
47
|
}
|
|
35
48
|
/**
|
package/dist/route-catalog.js
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
function mergeParameters(pathItemParameters, operationParameters) {
|
|
2
|
+
if (!pathItemParameters || pathItemParameters.length === 0) {
|
|
3
|
+
return operationParameters;
|
|
4
|
+
}
|
|
5
|
+
if (!operationParameters || operationParameters.length === 0) {
|
|
6
|
+
return pathItemParameters;
|
|
7
|
+
}
|
|
8
|
+
const parameters = new Map();
|
|
9
|
+
for (const parameter of pathItemParameters) {
|
|
10
|
+
parameters.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
11
|
+
}
|
|
12
|
+
for (const parameter of operationParameters) {
|
|
13
|
+
parameters.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
14
|
+
}
|
|
15
|
+
return [...parameters.values()];
|
|
16
|
+
}
|
|
1
17
|
/**
|
|
2
18
|
* Adapts an OpenAPI-like document to the client package's narrow route
|
|
3
19
|
* catalog. The document is retained by reference so live OpenAPI reloads are
|
|
@@ -12,7 +28,18 @@ export function createOpenApiRouteCatalog(document) {
|
|
|
12
28
|
return undefined;
|
|
13
29
|
}
|
|
14
30
|
const pathItem = document.paths[matchingPath];
|
|
15
|
-
|
|
31
|
+
const operation = pathItem?.[method.toLowerCase()];
|
|
32
|
+
if (!operation) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
const pathItemParameters = pathItem?.parameters;
|
|
36
|
+
const parameters = mergeParameters(pathItemParameters, operation.parameters);
|
|
37
|
+
const consumes = operation.consumes ?? document.consumes;
|
|
38
|
+
if ((!pathItemParameters || pathItemParameters.length === 0) &&
|
|
39
|
+
consumes === operation.consumes) {
|
|
40
|
+
return operation;
|
|
41
|
+
}
|
|
42
|
+
return { ...operation, consumes, parameters };
|
|
16
43
|
},
|
|
17
44
|
listPaths() {
|
|
18
45
|
return Object.keys(document.paths);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@counterfact/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Build and send reusable OpenAPI-aware HTTP requests without starting Counterfact.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -51,4 +51,4 @@
|
|
|
51
51
|
"test": "node --experimental-vm-modules ../../node_modules/jest-cli/bin/jest.js --config ../../jest.config.js packages/client/test",
|
|
52
52
|
"test:packed-consumer": "node test/package/client-consumer-smoke.mjs"
|
|
53
53
|
}
|
|
54
|
-
}
|
|
54
|
+
}
|