sheridan-typespec-aspnet 0.2.1 → 0.4.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/README.md +11 -4
- package/dist/src/emitter.js +104 -5
- package/dist/src/lib.d.ts +47 -2
- package/dist/src/lib.js +18 -0
- package/dist/src/model/collect-types.d.ts +3 -1
- package/dist/src/model/collect-types.js +1 -1
- package/dist/src/model/collect.js +56 -6
- package/dist/src/model/types.d.ts +12 -0
- package/dist/src/naming/names.d.ts +1 -1
- package/dist/src/naming/names.js +13 -3
- package/dist/src/naming/services.d.ts +11 -1
- package/dist/src/naming/services.js +18 -3
- package/dist/src/render/controllers/controllers.d.ts +20 -0
- package/dist/src/render/controllers/controllers.js +559 -0
- package/dist/src/render/controllers/results.d.ts +10 -0
- package/dist/src/render/controllers/results.js +82 -0
- package/dist/src/render/minimal/endpoints.d.ts +14 -0
- package/dist/src/render/minimal/endpoints.js +161 -0
- package/dist/src/render/minimal/results.d.ts +11 -0
- package/dist/src/render/minimal/results.js +90 -0
- package/dist/src/render/shared/api-setup.d.ts +9 -1
- package/dist/src/render/shared/api-setup.js +165 -11
- package/dist/src/render/shared/binding.d.ts +43 -0
- package/dist/src/render/shared/binding.js +426 -0
- package/dist/src/render/shared/body-formats.d.ts +18 -0
- package/dist/src/render/shared/body-formats.js +561 -0
- package/dist/src/render/shared/converters.js +57 -4
- package/dist/src/render/shared/documentation.d.ts +18 -0
- package/dist/src/render/shared/documentation.js +112 -0
- package/dist/src/render/shared/headers.d.ts +7 -0
- package/dist/src/render/shared/headers.js +52 -0
- package/dist/src/render/shared/models.js +5 -23
- package/dist/src/render/shared/openapi.d.ts +1 -0
- package/dist/src/render/shared/openapi.js +333 -0
- package/dist/src/render/shared/parameters.d.ts +3 -0
- package/dist/src/render/shared/parameters.js +224 -0
- package/dist/src/render/shared/references.d.ts +3 -0
- package/dist/src/render/shared/references.js +18 -0
- package/dist/src/render/shared/request-selector.d.ts +1 -0
- package/dist/src/render/shared/request-selector.js +139 -0
- package/dist/src/render/shared/responses.d.ts +55 -0
- package/dist/src/render/shared/responses.js +130 -0
- package/dist/src/render/shared/routes.d.ts +37 -0
- package/dist/src/render/shared/routes.js +274 -0
- package/dist/src/render/shared/validation.d.ts +6 -1
- package/dist/src/render/shared/validation.js +60 -0
- package/dist/src/scaffold/projects.d.ts +1 -1
- package/dist/src/scaffold/projects.js +4 -3
- package/package.json +2 -2
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
import { csharpFile, stringLiteral } from "../shared/writer.js";
|
|
2
|
+
const mvc = "global::Microsoft.AspNetCore.Mvc";
|
|
3
|
+
const task = "global::System.Threading.Tasks.Task";
|
|
4
|
+
const verbs = {
|
|
5
|
+
get: "HttpGet",
|
|
6
|
+
put: "HttpPut",
|
|
7
|
+
post: "HttpPost",
|
|
8
|
+
patch: "HttpPatch",
|
|
9
|
+
delete: "HttpDelete",
|
|
10
|
+
head: "HttpHead",
|
|
11
|
+
};
|
|
12
|
+
const attributes = {
|
|
13
|
+
route: "FromRoute",
|
|
14
|
+
query: "FromQuery",
|
|
15
|
+
header: "FromHeader",
|
|
16
|
+
body: "FromBody",
|
|
17
|
+
};
|
|
18
|
+
/** Route parameters MVC takes for its own use. */
|
|
19
|
+
const reserved = /^(action|area|controller|handler|page)$/i;
|
|
20
|
+
const parameterInRoute = /(?<!\{)(\{(?:\*\*)?)([^{}?*]+)(?=\??\})/g;
|
|
21
|
+
/**
|
|
22
|
+
* A new name for each reserved parameter of a route: its own with as many leading `_` as it takes
|
|
23
|
+
* to be unlike the others.
|
|
24
|
+
*/
|
|
25
|
+
function renames(segments) {
|
|
26
|
+
const names = segments.flatMap((segment) => [...segment.text.matchAll(parameterInRoute)].map((found) => found[2]));
|
|
27
|
+
const taken = new Set(names.map((name) => name.toLowerCase()));
|
|
28
|
+
return new Map(names
|
|
29
|
+
.filter((name) => reserved.test(name))
|
|
30
|
+
.map((name) => {
|
|
31
|
+
let wanted = `_${name}`;
|
|
32
|
+
while (taken.has(wanted.toLowerCase()))
|
|
33
|
+
wanted = `_${wanted}`;
|
|
34
|
+
return [name, wanted];
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
function declaration({ source, wireName, type, name, attributes: checks }, renamed, rootNamespace) {
|
|
38
|
+
const attribute = attributes[source];
|
|
39
|
+
const sent = (source === "route" && renamed.get(wireName)) || wireName;
|
|
40
|
+
const named = sent === undefined ? "" : `(Name = ${stringLiteral(sent)})`;
|
|
41
|
+
// MVC reads these by rules of its own, so binders read them as Minimal APIs do.
|
|
42
|
+
// The emitter says what is required, as the host can change what MVC makes of nullability.
|
|
43
|
+
const optional = type.endsWith("?") || (source !== "body" && type.endsWith("[]"));
|
|
44
|
+
const required = optional ? "" : "Required";
|
|
45
|
+
const binder = source === "cancellation"
|
|
46
|
+
? undefined
|
|
47
|
+
: `${required}Wire${source === "body" ? "Body" : "Value"}Binder`;
|
|
48
|
+
const list = [
|
|
49
|
+
...(attribute ? [`${mvc}.${attribute}Attribute${named}`] : []),
|
|
50
|
+
...(binder
|
|
51
|
+
? [`${mvc}.ModelBinderAttribute(typeof(global::${rootNamespace}.Requests.${binder}))`]
|
|
52
|
+
: []),
|
|
53
|
+
...(checks ?? []),
|
|
54
|
+
];
|
|
55
|
+
return `${list.map((item) => `[${item}] `).join("")}${type} ${name}`;
|
|
56
|
+
}
|
|
57
|
+
const list = (values) => values.map(stringLiteral).join(", ");
|
|
58
|
+
/** A route template, where square brackets would otherwise name a token. */
|
|
59
|
+
const template = (segments, renamed) => segments
|
|
60
|
+
.map((segment) => segment.text
|
|
61
|
+
.replace(parameterInRoute, (_, open, name) => `${open}${renamed.get(name) ?? name}`)
|
|
62
|
+
.replaceAll("[", "[[")
|
|
63
|
+
.replaceAll("]", "]]"))
|
|
64
|
+
.join("/");
|
|
65
|
+
/** The leading segments every route of a group starts with, which the controller takes. */
|
|
66
|
+
function commonPrefix(routes) {
|
|
67
|
+
let length = 0;
|
|
68
|
+
while (routes.every((route) => route[length] !== undefined &&
|
|
69
|
+
!route[length].trailing &&
|
|
70
|
+
route[length].text === routes[0][length].text)) {
|
|
71
|
+
length++;
|
|
72
|
+
}
|
|
73
|
+
return length;
|
|
74
|
+
}
|
|
75
|
+
function conditionAttributes(rootNamespace, found) {
|
|
76
|
+
const routing = `global::${rootNamespace}.Routing`;
|
|
77
|
+
return [
|
|
78
|
+
...found.values.map((v) => `${routing}.RequiresValueAttribute(${v.in === "header"}, ${stringLiteral(v.name)}, ${stringLiteral(v.value)}, ${v.ignoreCase})`),
|
|
79
|
+
...(found.contentTypes.length
|
|
80
|
+
? [`${routing}.RequiresContentTypeAttribute(${list(found.contentTypes)})`]
|
|
81
|
+
: []),
|
|
82
|
+
];
|
|
83
|
+
}
|
|
84
|
+
const conventionName = "DocumentationAttribute";
|
|
85
|
+
/** What an endpoint of the same operation is told by calls. */
|
|
86
|
+
function metadata({ name, summary, description, operation }, tags) {
|
|
87
|
+
const http = "global::Microsoft.AspNetCore.Http";
|
|
88
|
+
return [
|
|
89
|
+
`new global::Microsoft.AspNetCore.Routing.EndpointNameMetadata(${stringLiteral(name)})`,
|
|
90
|
+
...(summary ? [`new ${http}.EndpointSummaryAttribute(${stringLiteral(summary)})`] : []),
|
|
91
|
+
...(description
|
|
92
|
+
? [`new ${http}.EndpointDescriptionAttribute(${stringLiteral(description)})`]
|
|
93
|
+
: []),
|
|
94
|
+
...(tags.length ? [`new ${http}.TagsAttribute(${list(tags)})`] : []),
|
|
95
|
+
...(operation ? [operation] : []),
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A convention adding to each action what an attribute cannot hold, where OpenAPI reads it as it
|
|
100
|
+
* does for an endpoint.
|
|
101
|
+
*/
|
|
102
|
+
function convention(described) {
|
|
103
|
+
const models = "global::Microsoft.AspNetCore.Mvc.ApplicationModels";
|
|
104
|
+
return [
|
|
105
|
+
" /// <summary>Names and describes the actions.</summary>",
|
|
106
|
+
" [global::System.AttributeUsage(global::System.AttributeTargets.Class)]",
|
|
107
|
+
` internal sealed class ${conventionName} : global::System.Attribute, ${models}.IControllerModelConvention`,
|
|
108
|
+
" {",
|
|
109
|
+
` public void Apply(${models}.ControllerModel controller)`,
|
|
110
|
+
" {",
|
|
111
|
+
" foreach (var action in controller.Actions)",
|
|
112
|
+
" {",
|
|
113
|
+
" object[] metadata = action.ActionMethod.Name switch",
|
|
114
|
+
" {",
|
|
115
|
+
...described.map(([action, items]) => [
|
|
116
|
+
` ${stringLiteral(action)} => new object[]`,
|
|
117
|
+
" {",
|
|
118
|
+
...items.map((item) => ` ${item},`),
|
|
119
|
+
" },",
|
|
120
|
+
].join("\n")),
|
|
121
|
+
" _ => global::System.Array.Empty<object>(),",
|
|
122
|
+
" };",
|
|
123
|
+
" foreach (var selector in action.Selectors)",
|
|
124
|
+
" {",
|
|
125
|
+
" foreach (var item in metadata)",
|
|
126
|
+
" {",
|
|
127
|
+
" selector.EndpointMetadata.Add(item);",
|
|
128
|
+
" }",
|
|
129
|
+
" }",
|
|
130
|
+
" }",
|
|
131
|
+
" }",
|
|
132
|
+
" }",
|
|
133
|
+
];
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* A method that is never called. `AddValidation()` learns which types to check from the calls that
|
|
137
|
+
* map endpoints, so one names the type of each body.
|
|
138
|
+
*/
|
|
139
|
+
function discovery(bodies) {
|
|
140
|
+
const builder = "global::Microsoft.AspNetCore.Builder";
|
|
141
|
+
return [
|
|
142
|
+
" // Never called: it tells AddValidation() which types the actions take.",
|
|
143
|
+
" internal static void DescribeToValidation(",
|
|
144
|
+
" global::Microsoft.AspNetCore.Routing.IEndpointRouteBuilder routes)",
|
|
145
|
+
" {",
|
|
146
|
+
...bodies.map((type) => ` ${builder}.EndpointRouteBuilderExtensions.MapPost(routes, "", (${type} body) => { });`),
|
|
147
|
+
" }",
|
|
148
|
+
];
|
|
149
|
+
}
|
|
150
|
+
/** Renders the controller of every group. */
|
|
151
|
+
export function renderControllers(rootNamespace, services, routing, handle) {
|
|
152
|
+
return services.map((service) => {
|
|
153
|
+
const { name, file, handlers } = service.endpoints;
|
|
154
|
+
/** The types of the bodies, which validation must be told of. */
|
|
155
|
+
const bodies = new Set();
|
|
156
|
+
const tags = service.group.tags ?? [service.group.name].filter(Boolean);
|
|
157
|
+
/** What each action is said to be, by the name of its method. */
|
|
158
|
+
const described = [];
|
|
159
|
+
const routes = service.operations.map((o) => routing.routes.get(o.operation));
|
|
160
|
+
const prefix = commonPrefix(routes.map((route) => route.segments));
|
|
161
|
+
const contract = `global::${service.namespace}.${service.name}`;
|
|
162
|
+
// Renamed across the group, so that the controller's route and its actions agree.
|
|
163
|
+
const renamed = renames(routes.flatMap((route) => route.segments));
|
|
164
|
+
const actions = service.operations.map(({ operation, method }, index) => {
|
|
165
|
+
const { binding, arms, responses, documentation } = handle(service, index);
|
|
166
|
+
const own = [...new Set([...tags, ...(operation.tags ?? [])])];
|
|
167
|
+
described.push([handlers[index], metadata(documentation, own)]);
|
|
168
|
+
for (const parameter of binding.parameters) {
|
|
169
|
+
if (parameter.source === "body")
|
|
170
|
+
bodies.add(parameter.type);
|
|
171
|
+
}
|
|
172
|
+
const route = template(routes[index].segments.slice(prefix), renamed);
|
|
173
|
+
const found = routing.conditions.get(operation);
|
|
174
|
+
// As ASP.NET Core says of a Minimal API handler that takes a body, so that routing refuses
|
|
175
|
+
// another content type in both styles.
|
|
176
|
+
const json = binding.parameters.some((p) => p.source === "body") ? ["application/json"] : [];
|
|
177
|
+
const declared = binding.accepts.length ? binding.accepts : json;
|
|
178
|
+
const accepts = found?.accepted.length ? found.accepted : declared;
|
|
179
|
+
const marks = [
|
|
180
|
+
`${mvc}.${verbs[operation.verb]}Attribute${route || !prefix ? `(${stringLiteral(route)})` : ""}`,
|
|
181
|
+
...(accepts.length ? [`${mvc}.ConsumesAttribute(${list(accepts)})`] : []),
|
|
182
|
+
...(binding.converted
|
|
183
|
+
? [
|
|
184
|
+
// The shape is named, as an attribute cannot hold it.
|
|
185
|
+
`global::${rootNamespace}.Requests.BodyFormats.ReadAttribute(${list([
|
|
186
|
+
binding.converted.shape.split(".").at(-1),
|
|
187
|
+
...binding.converted.types,
|
|
188
|
+
])})`,
|
|
189
|
+
]
|
|
190
|
+
: []),
|
|
191
|
+
...(found ? conditionAttributes(rootNamespace, found) : []),
|
|
192
|
+
...responses,
|
|
193
|
+
];
|
|
194
|
+
return [
|
|
195
|
+
...marks.map((mark) => ` [${mark}]`),
|
|
196
|
+
` public async ${task}<${mvc}.IActionResult> ${handlers[index]}(`,
|
|
197
|
+
`${binding.parameters.map((p) => ` ${declaration(p, renamed, rootNamespace)}`).join(",\n")})`,
|
|
198
|
+
" {",
|
|
199
|
+
` var ${binding.result} = await this._service.${method}(`,
|
|
200
|
+
`${binding.values.map((value) => ` ${value}`).join(",\n")});`,
|
|
201
|
+
` return ${binding.result} switch`,
|
|
202
|
+
" {",
|
|
203
|
+
...arms.map((arm) => ` ${arm},`),
|
|
204
|
+
' null => throw new global::System.InvalidOperationException("The service returned no result."),',
|
|
205
|
+
" };",
|
|
206
|
+
" }",
|
|
207
|
+
].join("\n");
|
|
208
|
+
});
|
|
209
|
+
const base = template(routes[0].segments.slice(0, prefix), renamed);
|
|
210
|
+
const body = [
|
|
211
|
+
`/// <summary>Routes requests to <c>${service.name}</c>.</summary>`,
|
|
212
|
+
`[${mvc}.ApiControllerAttribute]`,
|
|
213
|
+
// What the spec answers without a body keeps none.
|
|
214
|
+
`[${mvc}.SkipStatusCodePagesAttribute]`,
|
|
215
|
+
`[global::${rootNamespace}.Requests.ValidateArgumentsAttribute]`,
|
|
216
|
+
`[global::${rootNamespace}.Requests.RefusedRequestsAttribute]`,
|
|
217
|
+
`[global::${service.namespace}.${name}.${conventionName}]`,
|
|
218
|
+
// An error the spec gives no body has none, where MVC would describe a problem.
|
|
219
|
+
`[${mvc}.ProducesErrorResponseTypeAttribute(typeof(void))]`,
|
|
220
|
+
...(prefix ? [`[${mvc}.RouteAttribute(${stringLiteral(base)})]`] : []),
|
|
221
|
+
`public sealed class ${name} : ${mvc}.ControllerBase`,
|
|
222
|
+
"{",
|
|
223
|
+
` private readonly ${contract} _service;`,
|
|
224
|
+
"",
|
|
225
|
+
" /// <summary>Takes the service the actions call.</summary>",
|
|
226
|
+
` public ${name}(${contract} service) => this._service = service;`,
|
|
227
|
+
"",
|
|
228
|
+
// The actions have no documentation comments, whatever a project asks for.
|
|
229
|
+
"#pragma warning disable CS1591",
|
|
230
|
+
actions.join("\n\n"),
|
|
231
|
+
"#pragma warning restore CS1591",
|
|
232
|
+
...(bodies.size ? ["", ...discovery([...bodies])] : []),
|
|
233
|
+
"",
|
|
234
|
+
...convention(described),
|
|
235
|
+
"}",
|
|
236
|
+
];
|
|
237
|
+
return { path: file, content: csharpFile(service.namespace, body.join("\n")) };
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
/** The generated action results for what MVC's do not send. */
|
|
241
|
+
export function renderActionResults(rootNamespace) {
|
|
242
|
+
return csharpFile(`${rootNamespace}.Responses`, `/// <summary>
|
|
243
|
+
/// A status without a body. MVC's own status results gain a problem body for an error.
|
|
244
|
+
/// </summary>
|
|
245
|
+
public sealed class BodilessActionResult(int statusCode)
|
|
246
|
+
: global::Microsoft.AspNetCore.Mvc.IActionResult,
|
|
247
|
+
global::Microsoft.AspNetCore.Mvc.Infrastructure.IStatusCodeActionResult
|
|
248
|
+
{
|
|
249
|
+
public int StatusCode { get; } = statusCode;
|
|
250
|
+
|
|
251
|
+
int? global::Microsoft.AspNetCore.Mvc.Infrastructure.IStatusCodeActionResult.StatusCode => StatusCode;
|
|
252
|
+
|
|
253
|
+
public global::System.Threading.Tasks.Task ExecuteResultAsync(
|
|
254
|
+
global::Microsoft.AspNetCore.Mvc.ActionContext context)
|
|
255
|
+
{
|
|
256
|
+
context.HttpContext.Response.StatusCode = StatusCode;
|
|
257
|
+
return global::System.Threading.Tasks.Task.CompletedTask;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/// <summary>A body of bytes with any status.</summary>
|
|
262
|
+
public sealed class BytesActionResult(int statusCode, byte[]? body, string contentType)
|
|
263
|
+
: global::Microsoft.AspNetCore.Mvc.IActionResult,
|
|
264
|
+
global::Microsoft.AspNetCore.Mvc.Infrastructure.IStatusCodeActionResult
|
|
265
|
+
{
|
|
266
|
+
public int StatusCode { get; } = statusCode;
|
|
267
|
+
|
|
268
|
+
int? global::Microsoft.AspNetCore.Mvc.Infrastructure.IStatusCodeActionResult.StatusCode => StatusCode;
|
|
269
|
+
|
|
270
|
+
public byte[]? Body { get; } = body;
|
|
271
|
+
|
|
272
|
+
public string ContentType { get; } = contentType;
|
|
273
|
+
|
|
274
|
+
public global::System.Threading.Tasks.Task ExecuteResultAsync(
|
|
275
|
+
global::Microsoft.AspNetCore.Mvc.ActionContext context) =>
|
|
276
|
+
((global::Microsoft.AspNetCore.Http.IResult)new BytesHttpResult(StatusCode, Body, ContentType))
|
|
277
|
+
.ExecuteAsync(context.HttpContext);
|
|
278
|
+
}`);
|
|
279
|
+
}
|
|
280
|
+
/** The generated binders and filter, which bind and check requests as Minimal APIs do. */
|
|
281
|
+
export function renderActionBinding(rootNamespace) {
|
|
282
|
+
return csharpFile(`${rootNamespace}.Requests`, `// Inside the namespace, so that a type in the spec cannot hide these.
|
|
283
|
+
using global::System;
|
|
284
|
+
using global::System.Collections.Concurrent;
|
|
285
|
+
using global::System.Collections.Generic;
|
|
286
|
+
using global::System.Globalization;
|
|
287
|
+
using global::System.Linq;
|
|
288
|
+
using global::System.Reflection;
|
|
289
|
+
using global::System.Runtime.CompilerServices;
|
|
290
|
+
using global::System.Runtime.ExceptionServices;
|
|
291
|
+
using global::System.Text.Json;
|
|
292
|
+
using global::System.Threading.Tasks;
|
|
293
|
+
using global::Microsoft.AspNetCore.Http;
|
|
294
|
+
using global::Microsoft.AspNetCore.Http.Features;
|
|
295
|
+
using global::Microsoft.AspNetCore.Mvc;
|
|
296
|
+
using global::Microsoft.AspNetCore.Mvc.Controllers;
|
|
297
|
+
using global::Microsoft.AspNetCore.Mvc.Filters;
|
|
298
|
+
using global::Microsoft.AspNetCore.Mvc.ModelBinding;
|
|
299
|
+
using global::Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
|
300
|
+
using global::Microsoft.Extensions.DependencyInjection;
|
|
301
|
+
using global::Microsoft.Extensions.Options;
|
|
302
|
+
using global::Microsoft.Extensions.Validation;
|
|
303
|
+
|
|
304
|
+
/// <summary>
|
|
305
|
+
/// Reads a value of the route, query or headers as Minimal APIs do: an empty value is kept,
|
|
306
|
+
/// repeated values are joined, and a number or boolean must be one.
|
|
307
|
+
/// </summary>
|
|
308
|
+
internal class WireValueBinder : IModelBinder
|
|
309
|
+
{
|
|
310
|
+
/// <summary>True when a request must send the value.</summary>
|
|
311
|
+
protected virtual bool Required => false;
|
|
312
|
+
|
|
313
|
+
public Task BindModelAsync(ModelBindingContext bindingContext)
|
|
314
|
+
{
|
|
315
|
+
var request = bindingContext.HttpContext.Request;
|
|
316
|
+
var name = bindingContext.BinderModelName ?? bindingContext.FieldName;
|
|
317
|
+
string?[] values;
|
|
318
|
+
if (bindingContext.BindingSource == BindingSource.Path)
|
|
319
|
+
{
|
|
320
|
+
// A catch-all that matched nothing holds no text.
|
|
321
|
+
var found = Convert.ToString(
|
|
322
|
+
bindingContext.ActionContext.RouteData.Values.GetValueOrDefault(name),
|
|
323
|
+
CultureInfo.InvariantCulture);
|
|
324
|
+
values = string.IsNullOrEmpty(found) ? [] : [found];
|
|
325
|
+
}
|
|
326
|
+
else
|
|
327
|
+
{
|
|
328
|
+
values = bindingContext.BindingSource == BindingSource.Header
|
|
329
|
+
? request.Headers[name].ToArray()
|
|
330
|
+
: request.Query[name].ToArray();
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
var type = bindingContext.ModelType;
|
|
334
|
+
object? model;
|
|
335
|
+
if (type.IsArray)
|
|
336
|
+
{
|
|
337
|
+
var item = type.GetElementType()!;
|
|
338
|
+
var items = Array.CreateInstance(item, values.Length);
|
|
339
|
+
for (var index = 0; index < values.Length; index++)
|
|
340
|
+
{
|
|
341
|
+
items.SetValue(Read(item, values[index] ?? "", name), index);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
model = items;
|
|
345
|
+
}
|
|
346
|
+
else if (values.Length > 0)
|
|
347
|
+
{
|
|
348
|
+
var text = values.Length == 1 ? values[0] ?? "" : string.Join(",", values);
|
|
349
|
+
model = Read(type, text, name);
|
|
350
|
+
}
|
|
351
|
+
else if (Required)
|
|
352
|
+
{
|
|
353
|
+
throw new BadHttpRequestException($"The value \\"{name}\\" is required.");
|
|
354
|
+
}
|
|
355
|
+
else
|
|
356
|
+
{
|
|
357
|
+
return Task.CompletedTask;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
Bound.Set(bindingContext, model);
|
|
361
|
+
return Task.CompletedTask;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private static object Read(Type type, string text, string name)
|
|
365
|
+
{
|
|
366
|
+
var held = Nullable.GetUnderlyingType(type) ?? type;
|
|
367
|
+
if (held == typeof(string))
|
|
368
|
+
{
|
|
369
|
+
return text;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (held == typeof(bool))
|
|
373
|
+
{
|
|
374
|
+
return bool.TryParse(text, out var flag) ? flag : throw Invalid(name);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
return Type.GetTypeCode(held) switch
|
|
378
|
+
{
|
|
379
|
+
TypeCode.SByte => Number<sbyte>(text, name),
|
|
380
|
+
TypeCode.Int16 => Number<short>(text, name),
|
|
381
|
+
TypeCode.Int32 => Number<int>(text, name),
|
|
382
|
+
TypeCode.Int64 => Number<long>(text, name),
|
|
383
|
+
TypeCode.Byte => Number<byte>(text, name),
|
|
384
|
+
TypeCode.UInt16 => Number<ushort>(text, name),
|
|
385
|
+
TypeCode.UInt32 => Number<uint>(text, name),
|
|
386
|
+
TypeCode.UInt64 => Number<ulong>(text, name),
|
|
387
|
+
TypeCode.Single => Number<float>(text, name),
|
|
388
|
+
TypeCode.Double => Number<double>(text, name),
|
|
389
|
+
TypeCode.Decimal => Number<decimal>(text, name),
|
|
390
|
+
_ => throw new InvalidOperationException($"A value of {held} cannot be read."),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private static T Number<T>(string text, string name)
|
|
395
|
+
where T : IParsable<T> =>
|
|
396
|
+
T.TryParse(text, CultureInfo.InvariantCulture, out var number) ? number : throw Invalid(name);
|
|
397
|
+
|
|
398
|
+
private static BadHttpRequestException Invalid(string name) =>
|
|
399
|
+
new($"The value \\"{name}\\" is not valid.");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/// <summary>A value of the route, query or headers that a request must send.</summary>
|
|
403
|
+
internal sealed class RequiredWireValueBinder : WireValueBinder
|
|
404
|
+
{
|
|
405
|
+
protected override bool Required => true;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/// <summary>A JSON body that a request must send.</summary>
|
|
409
|
+
internal sealed class RequiredWireBodyBinder(IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions> json)
|
|
410
|
+
: WireBodyBinder(json)
|
|
411
|
+
{
|
|
412
|
+
protected override bool Required => true;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/// <summary>Reads a JSON body as Minimal APIs do.</summary>
|
|
416
|
+
internal class WireBodyBinder(IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions> json)
|
|
417
|
+
: IModelBinder
|
|
418
|
+
{
|
|
419
|
+
/// <summary>True when a request must send a body.</summary>
|
|
420
|
+
protected virtual bool Required => false;
|
|
421
|
+
|
|
422
|
+
public async Task BindModelAsync(ModelBindingContext bindingContext)
|
|
423
|
+
{
|
|
424
|
+
var context = bindingContext.HttpContext;
|
|
425
|
+
var request = context.Request;
|
|
426
|
+
object? model = null;
|
|
427
|
+
if (context.Features.Get<IHttpRequestBodyDetectionFeature>()?.CanHaveBody == true)
|
|
428
|
+
{
|
|
429
|
+
if (!request.HasJsonContentType())
|
|
430
|
+
{
|
|
431
|
+
throw new BadHttpRequestException("A JSON body is expected.", 415);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
try
|
|
435
|
+
{
|
|
436
|
+
model = await request.ReadFromJsonAsync(
|
|
437
|
+
bindingContext.ModelType, json.Value.SerializerOptions, context.RequestAborted);
|
|
438
|
+
}
|
|
439
|
+
catch (Exception exception) when (exception is JsonException
|
|
440
|
+
|| (exception is NotSupportedException && exception.Source == "System.Text.Json"))
|
|
441
|
+
{
|
|
442
|
+
// Also JSON naming no kind of an abstract model.
|
|
443
|
+
throw new BadHttpRequestException("The body cannot be read.", 400, exception);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (model is null && Required)
|
|
448
|
+
{
|
|
449
|
+
throw new BadHttpRequestException("A body is required.");
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
Bound.Set(bindingContext, model);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
internal static class Bound
|
|
457
|
+
{
|
|
458
|
+
/// <summary>Gives the action a value, which MVC is not to check.</summary>
|
|
459
|
+
public static void Set(ModelBindingContext context, object? model)
|
|
460
|
+
{
|
|
461
|
+
if (model is not null)
|
|
462
|
+
{
|
|
463
|
+
context.ValidationState[model] = new ValidationStateEntry { SuppressValidation = true };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
context.Result = ModelBindingResult.Success(model);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/// <summary>
|
|
471
|
+
/// Keeps a refused request from the exception filters of the host, which Minimal APIs do not run,
|
|
472
|
+
/// so that it is answered as there.
|
|
473
|
+
/// </summary>
|
|
474
|
+
[AttributeUsage(AttributeTargets.Class)]
|
|
475
|
+
internal sealed class RefusedRequestsAttribute : Attribute, IExceptionFilter
|
|
476
|
+
{
|
|
477
|
+
public void OnException(ExceptionContext context)
|
|
478
|
+
{
|
|
479
|
+
if (context.Exception is BadHttpRequestException or RequestInvalidException)
|
|
480
|
+
{
|
|
481
|
+
// Thrown again once the filters are done, for the middleware to answer.
|
|
482
|
+
context.Result = new Rethrown(ExceptionDispatchInfo.Capture(context.Exception));
|
|
483
|
+
context.ExceptionHandled = true;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
private sealed class Rethrown(ExceptionDispatchInfo exception) : IActionResult
|
|
488
|
+
{
|
|
489
|
+
public Task ExecuteResultAsync(ActionContext context)
|
|
490
|
+
{
|
|
491
|
+
exception.Throw();
|
|
492
|
+
return Task.CompletedTask;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/// <summary>Checks the arguments of an action with the validation Minimal APIs use.</summary>
|
|
498
|
+
[AttributeUsage(AttributeTargets.Class)]
|
|
499
|
+
internal sealed class ValidateArgumentsAttribute : Attribute, IAsyncActionFilter
|
|
500
|
+
{
|
|
501
|
+
// Found once for each parameter, as for an endpoint.
|
|
502
|
+
private static readonly ConditionalWeakTable<
|
|
503
|
+
ValidationOptions, ConcurrentDictionary<ParameterInfo, IValidatableParameterInfo?>> Known = new();
|
|
504
|
+
|
|
505
|
+
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
|
506
|
+
{
|
|
507
|
+
var http = context.HttpContext;
|
|
508
|
+
var options = http.RequestServices.GetRequiredService<IOptions<ValidationOptions>>().Value;
|
|
509
|
+
var found = new ValidateContext { ValidationOptions = options, ServiceProvider = http.RequestServices };
|
|
510
|
+
var known = Known.GetOrCreateValue(options);
|
|
511
|
+
foreach (var parameter in context.ActionDescriptor.Parameters)
|
|
512
|
+
{
|
|
513
|
+
if (parameter is ControllerParameterDescriptor { ParameterInfo: var info }
|
|
514
|
+
&& known.GetOrAdd(
|
|
515
|
+
info,
|
|
516
|
+
asked => options.TryGetValidatableParameterInfo(asked, out var made) ? made : null)
|
|
517
|
+
is { } checks)
|
|
518
|
+
{
|
|
519
|
+
context.ActionArguments.TryGetValue(parameter.Name, out var value);
|
|
520
|
+
await checks.ValidateAsync(value, found, http.RequestAborted);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
if (found.ValidationErrors is { Count: > 0 } errors)
|
|
525
|
+
{
|
|
526
|
+
var messages = errors.ToDictionary(
|
|
527
|
+
error => error.Key, error => error.Value.Select(found => found.ErrorMessage).ToArray());
|
|
528
|
+
context.Result = new Invalid(new HttpValidationProblemDetails(messages) { Status = 400 });
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
await next();
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Written as the validation of Minimal APIs writes it.
|
|
536
|
+
private sealed class Invalid(HttpValidationProblemDetails problem) : IActionResult
|
|
537
|
+
{
|
|
538
|
+
public async Task ExecuteResultAsync(ActionContext context)
|
|
539
|
+
{
|
|
540
|
+
var http = context.HttpContext;
|
|
541
|
+
http.Response.StatusCode = 400;
|
|
542
|
+
var written = new ProblemDetailsContext { HttpContext = http, ProblemDetails = problem };
|
|
543
|
+
foreach (var writer in http.RequestServices.GetServices<IProblemDetailsWriter>())
|
|
544
|
+
{
|
|
545
|
+
// MVC's own writer leaves out the errors, and Minimal APIs do not have it.
|
|
546
|
+
if (writer.GetType().Assembly != typeof(ControllerBase).Assembly
|
|
547
|
+
&& writer.GetType().Namespace?.StartsWith("Microsoft.AspNetCore.Mvc") != true
|
|
548
|
+
&& writer.CanWrite(written))
|
|
549
|
+
{
|
|
550
|
+
await writer.WriteAsync(written);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
await http.Response.WriteAsJsonAsync(problem, http.RequestAborted);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}`);
|
|
559
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Program } from "@typespec/compiler";
|
|
2
|
+
import type { ApiModel } from "../../model/types.js";
|
|
3
|
+
import type { HeaderWriter } from "../shared/headers.js";
|
|
4
|
+
import type { ServiceContract } from "../shared/services.js";
|
|
5
|
+
export declare function actionResultWriter(program: Program, model: ApiModel, rootNamespace: string, headers: HeaderWriter): (operation: ServiceContract["operations"][number], value: string, context: string, namespace: string) => string[];
|
|
6
|
+
/**
|
|
7
|
+
* The attributes declaring the responses of an action. A range of statuses has none, as MVC names
|
|
8
|
+
* only single statuses and the default.
|
|
9
|
+
*/
|
|
10
|
+
export declare function responseAttributes(model: ApiModel, operation: ServiceContract["operations"][number]): string[];
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { arm, documentedCases, responseWriter } from "../shared/responses.js";
|
|
2
|
+
import { stringLiteral } from "../shared/writer.js";
|
|
3
|
+
const mvc = "global::Microsoft.AspNetCore.Mvc";
|
|
4
|
+
/**
|
|
5
|
+
* The result types of MVC with a body, for the statuses that have one of their own. 201 is left
|
|
6
|
+
* out, as `CreatedResult` replaces a `Location` header the spec declares.
|
|
7
|
+
*/
|
|
8
|
+
const withBody = {
|
|
9
|
+
200: "OkObjectResult",
|
|
10
|
+
202: "AcceptedResult",
|
|
11
|
+
400: "BadRequestObjectResult",
|
|
12
|
+
404: "NotFoundObjectResult",
|
|
13
|
+
409: "ConflictObjectResult",
|
|
14
|
+
422: "UnprocessableEntityObjectResult",
|
|
15
|
+
};
|
|
16
|
+
/** A `ControllerBase` helper for each of these statuses without a body. */
|
|
17
|
+
const helpers = { 200: "Ok()", 204: "NoContent()" };
|
|
18
|
+
export function actionResultWriter(program, model, rootNamespace, headers) {
|
|
19
|
+
const type = `${mvc}.IActionResult`;
|
|
20
|
+
const bodiless = (code) => `new global::${rootNamespace}.Responses.BodilessActionResult(${code})`;
|
|
21
|
+
const maker = {
|
|
22
|
+
empty({ fixed, code }) {
|
|
23
|
+
// `[ApiController]` gives an error status result a body, which the spec does not declare.
|
|
24
|
+
if (fixed === undefined || fixed >= 400) {
|
|
25
|
+
return { type, expression: bodiless(code) };
|
|
26
|
+
}
|
|
27
|
+
return { type, expression: `this.${helpers[fixed] ?? `StatusCode(${code})`}` };
|
|
28
|
+
},
|
|
29
|
+
json({ fixed, code }, held, body, contentType, nullable) {
|
|
30
|
+
const own = fixed === undefined ? undefined : withBody[fixed];
|
|
31
|
+
const location = own === "AcceptedResult" ? "(string?)null, " : "";
|
|
32
|
+
// The declared type keeps the discriminator of a derived model, and the content type is
|
|
33
|
+
// set so that the request cannot choose another.
|
|
34
|
+
const set = [
|
|
35
|
+
...(own ? [] : [`StatusCode = ${code}`]),
|
|
36
|
+
`DeclaredType = typeof(${held})`,
|
|
37
|
+
`ContentTypes = { ${stringLiteral(contentType ?? "application/json")} }`,
|
|
38
|
+
];
|
|
39
|
+
const made = own ? `${own}(${location}${body})` : `ObjectResult(${body})`;
|
|
40
|
+
const result = `new ${mvc}.${made} { ${set.join(", ")} }`;
|
|
41
|
+
// MVC would answer a null value with 204, where the status of the case must be kept.
|
|
42
|
+
const expression = nullable
|
|
43
|
+
? `(${body} is null ? (${type})${bodiless(code)} : ${result})`
|
|
44
|
+
: result;
|
|
45
|
+
return { type, expression };
|
|
46
|
+
},
|
|
47
|
+
text({ code }, text, contentType) {
|
|
48
|
+
const charset = /;\s*charset=/i.test(contentType) ? "" : "; charset=utf-8";
|
|
49
|
+
return {
|
|
50
|
+
type,
|
|
51
|
+
expression: `new ${mvc}.ContentResult { Content = ${text}, ContentType = ${stringLiteral(contentType + charset)}, StatusCode = ${code} }`,
|
|
52
|
+
};
|
|
53
|
+
},
|
|
54
|
+
bytes: ({ code }, body, contentType) => ({
|
|
55
|
+
type,
|
|
56
|
+
expression: `new global::${rootNamespace}.Responses.BytesActionResult(${code}, ${body}, ${stringLiteral(contentType)})`,
|
|
57
|
+
}),
|
|
58
|
+
};
|
|
59
|
+
const respond = responseWriter(program, model, rootNamespace, headers, maker);
|
|
60
|
+
/** The arms of the switch over an operation's result. `value` is a free name in the action. */
|
|
61
|
+
return (operation, value, context, namespace) => respond(operation, value, context).map(({ chosen, expression }) => arm(namespace, operation, chosen, value, expression));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The attributes declaring the responses of an action. A range of statuses has none, as MVC names
|
|
65
|
+
* only single statuses and the default.
|
|
66
|
+
*/
|
|
67
|
+
export function responseAttributes(model, operation) {
|
|
68
|
+
return documentedCases(model, operation).flatMap(({ key, body }) => {
|
|
69
|
+
if (key === "default") {
|
|
70
|
+
const type = body ? `typeof(${body.type})` : "typeof(void)";
|
|
71
|
+
return [`${mvc}.ProducesDefaultResponseTypeAttribute(${type})`];
|
|
72
|
+
}
|
|
73
|
+
if (!/^\d+$/.test(key))
|
|
74
|
+
return [];
|
|
75
|
+
// Not the generic attribute, whose type argument cannot say that an item may be null.
|
|
76
|
+
return [
|
|
77
|
+
body
|
|
78
|
+
? `${mvc}.ProducesResponseTypeAttribute(typeof(${body.type}), ${key}, ${stringLiteral(body.contentType)})`
|
|
79
|
+
: `${mvc}.ProducesResponseTypeAttribute(${key})`,
|
|
80
|
+
];
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ServiceName } from "../../naming/services.js";
|
|
2
|
+
import type { Binding } from "../shared/binding.js";
|
|
3
|
+
import type { Documentation } from "../shared/documentation.js";
|
|
4
|
+
import type { RenderedFile } from "../shared/models.js";
|
|
5
|
+
import type { Routing } from "../shared/routes.js";
|
|
6
|
+
import type { ResultMapping } from "./results.js";
|
|
7
|
+
/** What a handler reads and answers. */
|
|
8
|
+
export interface Handled {
|
|
9
|
+
binding: Binding;
|
|
10
|
+
result: ResultMapping;
|
|
11
|
+
documentation: Documentation;
|
|
12
|
+
}
|
|
13
|
+
/** Renders the endpoint class of every group. */
|
|
14
|
+
export declare function renderEndpoints(rootNamespace: string, services: ServiceName[], routing: Routing, handle: (service: ServiceName, index: number) => Handled): RenderedFile[];
|