sheridan-typespec-aspnet 0.3.0 → 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 +4 -4
- package/dist/src/emitter.js +72 -41
- package/dist/src/lib.d.ts +17 -2
- package/dist/src/lib.js +6 -0
- package/dist/src/model/collect.js +18 -4
- package/dist/src/model/types.d.ts +2 -0
- package/dist/src/naming/names.d.ts +1 -1
- package/dist/src/naming/names.js +2 -2
- package/dist/src/naming/services.d.ts +3 -3
- package/dist/src/naming/services.js +9 -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 +2 -2
- package/dist/src/render/minimal/endpoints.js +23 -1
- package/dist/src/render/minimal/results.js +33 -88
- package/dist/src/render/shared/api-setup.d.ts +4 -1
- package/dist/src/render/shared/api-setup.js +58 -24
- package/dist/src/render/shared/binding.d.ts +11 -1
- package/dist/src/render/shared/binding.js +52 -21
- 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/openapi.d.ts +1 -1
- package/dist/src/render/shared/openapi.js +88 -3
- package/dist/src/render/shared/request-selector.d.ts +1 -1
- package/dist/src/render/shared/request-selector.js +58 -5
- 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.js +36 -3
- package/package.json +1 -1
- package/dist/src/render/minimal/documentation.d.ts +0 -4
- package/dist/src/render/minimal/documentation.js +0 -107
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
// How form and XML request bodies are turned into JSON before they are bound, in either style
|
|
2
|
+
// (ADR 0085). The generated code needs the shape of each value, as neither format says whether a
|
|
3
|
+
// value is a number, text or a list.
|
|
4
|
+
import { resolveEncodedName, } from "@typespec/compiler";
|
|
5
|
+
import { mapScalar } from "./scalars.js";
|
|
6
|
+
import { stringLiteral } from "./writer.js";
|
|
7
|
+
const mediaType = (type) => type.split(";")[0].trim().toLowerCase();
|
|
8
|
+
export const isForm = (type) => mediaType(type) === "application/x-www-form-urlencoded";
|
|
9
|
+
export const isXml = (type) => /^(?:application|text)\/xml$|^application\/[\w.-]+\+xml$/.test(mediaType(type));
|
|
10
|
+
const numbers = new Set("sbyte short int long byte ushort uint ulong float double decimal".split(" "));
|
|
11
|
+
/** Why a body has no form or XML reading. */
|
|
12
|
+
class Refused extends Error {
|
|
13
|
+
}
|
|
14
|
+
/** Wraps the handler of a Minimal API endpoint. */
|
|
15
|
+
const endpointConvention = ` /// <summary>Reads the named content types of an endpoint's body as well as JSON.</summary>
|
|
16
|
+
public static void Accept(IEndpointConventionBuilder endpoint, BodyShape shape, string[] types)
|
|
17
|
+
{
|
|
18
|
+
// Wraps the handler itself, so that it does not matter where middleware sits.
|
|
19
|
+
endpoint.Finally(built =>
|
|
20
|
+
{
|
|
21
|
+
var next = built.RequestDelegate!;
|
|
22
|
+
built.RequestDelegate = async context =>
|
|
23
|
+
{
|
|
24
|
+
await ReadAsJson(context, shape, types);
|
|
25
|
+
await next(context);
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
`;
|
|
30
|
+
/** A filter of a controller's action. An attribute cannot hold a shape, so it names one. */
|
|
31
|
+
const actionFilter = (shapes) => ` /// <summary>Reads the named content types of an action's body as well as JSON.</summary>
|
|
32
|
+
[AttributeUsage(AttributeTargets.Method)]
|
|
33
|
+
public sealed class ReadAttribute(string shape, params string[] types)
|
|
34
|
+
: Attribute, IAsyncResourceFilter, IOrderedFilter
|
|
35
|
+
{
|
|
36
|
+
// After [Consumes], which judges the content type as it was sent.
|
|
37
|
+
public int Order => 1;
|
|
38
|
+
|
|
39
|
+
// Before MVC binds the body.
|
|
40
|
+
public async Task OnResourceExecutionAsync(
|
|
41
|
+
ResourceExecutingContext context, ResourceExecutionDelegate next)
|
|
42
|
+
{
|
|
43
|
+
await ReadAsJson(context.HttpContext, Shape(shape), types);
|
|
44
|
+
await next();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
private static BodyShape Shape(string name) => name switch
|
|
49
|
+
{
|
|
50
|
+
${shapes.map((name) => ` "${name}" => ${name},`).join("\n")}
|
|
51
|
+
_ => throw new InvalidOperationException($"There is no body shape named {name}."),
|
|
52
|
+
};
|
|
53
|
+
`;
|
|
54
|
+
export function bodyShapes(program, model, rootNamespace) {
|
|
55
|
+
/** Shapes by the name of the C# field holding each. */
|
|
56
|
+
const shapes = new Map();
|
|
57
|
+
const named = new Map();
|
|
58
|
+
const formats = `global::${rootNamespace}.Requests.BodyFormats`;
|
|
59
|
+
function add(key, make) {
|
|
60
|
+
let name = named.get(key);
|
|
61
|
+
if (name)
|
|
62
|
+
return name;
|
|
63
|
+
name = `Shape${named.size}`;
|
|
64
|
+
// Named first, so that a type holding itself ends here.
|
|
65
|
+
named.set(key, name);
|
|
66
|
+
shapes.set(name, { kind: "Any" });
|
|
67
|
+
shapes.set(name, make());
|
|
68
|
+
return name;
|
|
69
|
+
}
|
|
70
|
+
const leaf = (kind) => add(kind, () => ({ kind }));
|
|
71
|
+
function scalar(builtin, encoding) {
|
|
72
|
+
const wire = encoding?.wireType ?? builtin;
|
|
73
|
+
const mapped = wire === undefined ? undefined : mapScalar(wire)?.type;
|
|
74
|
+
if (mapped === "bool")
|
|
75
|
+
return leaf("Boolean");
|
|
76
|
+
return leaf(mapped && numbers.has(mapped) ? "Number" : "Text");
|
|
77
|
+
}
|
|
78
|
+
function literal(value) {
|
|
79
|
+
if (typeof value === "boolean")
|
|
80
|
+
return leaf("Boolean");
|
|
81
|
+
return leaf(typeof value === "number" ? "Number" : "Text");
|
|
82
|
+
}
|
|
83
|
+
function shape(ref, encoding, xml) {
|
|
84
|
+
switch (ref.kind) {
|
|
85
|
+
case "nullable":
|
|
86
|
+
return shape(ref.type, encoding, xml);
|
|
87
|
+
case "scalar":
|
|
88
|
+
return scalar(ref.name, encoding);
|
|
89
|
+
case "literal":
|
|
90
|
+
return literal(ref.value);
|
|
91
|
+
case "unknown":
|
|
92
|
+
return leaf("Any");
|
|
93
|
+
case "enumMember": {
|
|
94
|
+
const declared = model.types.get(ref.enum);
|
|
95
|
+
const member = declared.kind === "enum" && declared.members.find((m) => m.name === ref.member);
|
|
96
|
+
return literal(member ? member.value : "");
|
|
97
|
+
}
|
|
98
|
+
case "array": {
|
|
99
|
+
// Such as a pipe delimited list, which JSON holds as text.
|
|
100
|
+
if (encoding?.name?.startsWith("ArrayEncoding."))
|
|
101
|
+
return leaf("Text");
|
|
102
|
+
const item = shape(ref.element, encoding, xml);
|
|
103
|
+
return add(`Array ${item}`, () => ({ kind: "Array", item }));
|
|
104
|
+
}
|
|
105
|
+
case "record": {
|
|
106
|
+
const value = shape(ref.value, encoding, xml);
|
|
107
|
+
return add(`Map ${value}`, () => ({ kind: "Map", value }));
|
|
108
|
+
}
|
|
109
|
+
case "named":
|
|
110
|
+
return declaration(ref.id, encoding, xml);
|
|
111
|
+
default:
|
|
112
|
+
throw new Refused(ref.kind);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function declaration(id, encoding, xml) {
|
|
116
|
+
const type = model.types.get(id);
|
|
117
|
+
if (type.kind === "scalar")
|
|
118
|
+
return scalar(type.builtin, encoding);
|
|
119
|
+
if (type.kind === "enum")
|
|
120
|
+
return literal(type.members[0]?.value);
|
|
121
|
+
if (type.kind === "union") {
|
|
122
|
+
// A union is read only when all its cases are written alike.
|
|
123
|
+
const kinds = new Set(type.variants.map((variant) => {
|
|
124
|
+
const found = shape(variant.type, encoding, xml);
|
|
125
|
+
return shapes.get(found).kind;
|
|
126
|
+
}));
|
|
127
|
+
const [kind] = kinds;
|
|
128
|
+
if (!type.discriminator && kinds.size === 1) {
|
|
129
|
+
if (kind === "Text" || kind === "Number" || kind === "Boolean")
|
|
130
|
+
return leaf(kind);
|
|
131
|
+
}
|
|
132
|
+
throw new Refused("union");
|
|
133
|
+
}
|
|
134
|
+
// XML names are checked for each use, as one shape serves every operation.
|
|
135
|
+
if (xml)
|
|
136
|
+
refuseXmlNames(type);
|
|
137
|
+
return add(`${xml ? "xml " : ""}${id}`, () => object(type, xml));
|
|
138
|
+
}
|
|
139
|
+
/** A model, with what it inherits and, as a body may name any of them, what derives from it. */
|
|
140
|
+
function object(type, xml) {
|
|
141
|
+
const found = { kind: "Object", properties: new Map() };
|
|
142
|
+
const family = [];
|
|
143
|
+
for (let current = type; current; current = current.base ? model.types.get(current.base) : undefined) {
|
|
144
|
+
family.push(current);
|
|
145
|
+
}
|
|
146
|
+
let discriminator = family.find((member) => member.discriminator)?.discriminator;
|
|
147
|
+
if (type.discriminator) {
|
|
148
|
+
const bases = new Set([type.id]);
|
|
149
|
+
for (const other of model.types.values()) {
|
|
150
|
+
if (other.kind === "model" && other.base && bases.has(other.base)) {
|
|
151
|
+
bases.add(other.id);
|
|
152
|
+
family.push(other);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
discriminator = type.discriminator;
|
|
156
|
+
}
|
|
157
|
+
for (const member of family) {
|
|
158
|
+
if (xml)
|
|
159
|
+
refuseXmlNames(member);
|
|
160
|
+
for (const property of member.properties) {
|
|
161
|
+
const held = shape(property.type, property.encoding, xml);
|
|
162
|
+
const before = found.properties.get(property.wireName);
|
|
163
|
+
// A literal that narrows a property is written alike, so it shares the shape.
|
|
164
|
+
if (before && before.shape !== held) {
|
|
165
|
+
throw new Refused(`property "${property.wireName}" of several types`);
|
|
166
|
+
}
|
|
167
|
+
if (before)
|
|
168
|
+
continue;
|
|
169
|
+
// What only a derived model requires may be missing from the others.
|
|
170
|
+
const required = !property.optional && (member === type || !type.discriminator);
|
|
171
|
+
found.properties.set(property.wireName, { shape: held, required });
|
|
172
|
+
}
|
|
173
|
+
if (member.additionalProperties) {
|
|
174
|
+
found.extra = shape(member.additionalProperties, member.additionalEncoding, xml);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (discriminator && !found.properties.has(discriminator)) {
|
|
178
|
+
found.properties.set(discriminator, { shape: leaf("Text"), required: false });
|
|
179
|
+
}
|
|
180
|
+
return found;
|
|
181
|
+
}
|
|
182
|
+
/** Names and layouts of XML that would not be read as they are declared. */
|
|
183
|
+
function refuseXmlNames(type) {
|
|
184
|
+
const decorated = (source) => "decorators" in source &&
|
|
185
|
+
source.decorators.some((applied) => {
|
|
186
|
+
const namespace = applied.definition?.namespace;
|
|
187
|
+
return namespace?.name === "Xml" && namespace.namespace?.name === "TypeSpec";
|
|
188
|
+
});
|
|
189
|
+
if (decorated(type.source))
|
|
190
|
+
throw new Refused("@typespec/xml decorator");
|
|
191
|
+
for (const property of type.properties) {
|
|
192
|
+
if (decorated(property.source))
|
|
193
|
+
throw new Refused("@typespec/xml decorator");
|
|
194
|
+
if (property.source.kind !== "ModelProperty")
|
|
195
|
+
continue;
|
|
196
|
+
const source = property.source;
|
|
197
|
+
const name = resolveEncodedName(program, source, "application/xml");
|
|
198
|
+
if (name !== source.name && name !== property.wireName) {
|
|
199
|
+
throw new Refused(`XML name "${name}" from @encodedName`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
/**
|
|
205
|
+
* The expression naming the shape of a body, or what keeps it from being read as one of the
|
|
206
|
+
* content types.
|
|
207
|
+
*/
|
|
208
|
+
of(ref, contentTypes) {
|
|
209
|
+
const before = named.size;
|
|
210
|
+
try {
|
|
211
|
+
const found = shape(ref, undefined, contentTypes.some(isXml));
|
|
212
|
+
const kind = shapes.get(found).kind;
|
|
213
|
+
if (contentTypes.some(isForm) && kind !== "Object" && kind !== "Map") {
|
|
214
|
+
return { problem: "form body that is not a model or dictionary" };
|
|
215
|
+
}
|
|
216
|
+
return { shape: `${formats}.${found}` };
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (!(error instanceof Refused))
|
|
220
|
+
throw error;
|
|
221
|
+
// Shapes left half made would be taken as finished by a later body.
|
|
222
|
+
for (const [key, name] of [...named].slice(before)) {
|
|
223
|
+
named.delete(key);
|
|
224
|
+
shapes.delete(name);
|
|
225
|
+
}
|
|
226
|
+
return { problem: `${error.message} in a form or XML body` };
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
/** The generated file, when any body uses it. */
|
|
230
|
+
render(controllers = false) {
|
|
231
|
+
if (shapes.size === 0)
|
|
232
|
+
return undefined;
|
|
233
|
+
return renderBodyFormats(rootNamespace, shapes, controllers);
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function renderBodyFormats(rootNamespace, shapes, controllers) {
|
|
238
|
+
const fields = [...shapes].map(([name, { kind }]) => ` internal static readonly BodyShape ${name} = new(BodyKind.${kind});`);
|
|
239
|
+
const links = [...shapes].flatMap(([name, shape]) => {
|
|
240
|
+
if (shape.kind === "Array")
|
|
241
|
+
return [` ${name}.Item = ${shape.item};`];
|
|
242
|
+
if (shape.kind === "Map")
|
|
243
|
+
return [` ${name}.Extra = ${shape.value};`];
|
|
244
|
+
if (shape.kind !== "Object")
|
|
245
|
+
return [];
|
|
246
|
+
return [
|
|
247
|
+
...[...shape.properties].map(([wireName, { shape: held, required }]) => ` ${name}.Properties.Add(${stringLiteral(wireName)}, (${held}, ${required}));`),
|
|
248
|
+
...(shape.extra ? [` ${name}.Extra = ${shape.extra};`] : []),
|
|
249
|
+
];
|
|
250
|
+
});
|
|
251
|
+
return `// <auto-generated/>
|
|
252
|
+
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
253
|
+
#nullable enable
|
|
254
|
+
|
|
255
|
+
namespace ${rootNamespace}.Requests;
|
|
256
|
+
|
|
257
|
+
// Inside the namespace, so that a type in the spec cannot hide these.
|
|
258
|
+
using global::System;
|
|
259
|
+
using global::System.Collections.Generic;
|
|
260
|
+
using global::System.IO;
|
|
261
|
+
using global::System.Linq;
|
|
262
|
+
using global::System.Text;
|
|
263
|
+
using global::System.Text.Json;
|
|
264
|
+
using global::System.Text.Json.Nodes;
|
|
265
|
+
using global::System.Text.RegularExpressions;
|
|
266
|
+
using global::System.Threading.Tasks;
|
|
267
|
+
using global::System.Xml;
|
|
268
|
+
using global::System.Xml.Linq;
|
|
269
|
+
${controllers ? "using global::Microsoft.AspNetCore.Mvc.Filters;" : "using global::Microsoft.AspNetCore.Builder;"}
|
|
270
|
+
using global::Microsoft.AspNetCore.Http;
|
|
271
|
+
|
|
272
|
+
internal enum BodyKind
|
|
273
|
+
{
|
|
274
|
+
Text,
|
|
275
|
+
Number,
|
|
276
|
+
Boolean,
|
|
277
|
+
Any,
|
|
278
|
+
Object,
|
|
279
|
+
Array,
|
|
280
|
+
Map,
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/// <summary>What a value of a form or XML body holds.</summary>
|
|
284
|
+
internal sealed class BodyShape(BodyKind kind)
|
|
285
|
+
{
|
|
286
|
+
public BodyKind Kind { get; } = kind;
|
|
287
|
+
|
|
288
|
+
public Dictionary<string, (BodyShape Shape, bool Required)> Properties { get; } =
|
|
289
|
+
new(StringComparer.Ordinal);
|
|
290
|
+
|
|
291
|
+
/// <summary>The items of an array.</summary>
|
|
292
|
+
public BodyShape? Item { get; set; }
|
|
293
|
+
|
|
294
|
+
/// <summary>The values of a dictionary, or of properties the spec does not name.</summary>
|
|
295
|
+
public BodyShape? Extra { get; set; }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/// <summary>Turns form and XML request bodies into JSON, which is then bound and checked.</summary>
|
|
299
|
+
internal static class BodyFormats
|
|
300
|
+
{
|
|
301
|
+
private const int MaxDepth = 64;
|
|
302
|
+
|
|
303
|
+
// An XML body is held whole while it is read, so its size is limited, as a form value's is.
|
|
304
|
+
private const int MaxXmlBytes = 4 * 1024 * 1024;
|
|
305
|
+
|
|
306
|
+
private const string Form = "application/x-www-form-urlencoded";
|
|
307
|
+
|
|
308
|
+
private static readonly Regex JsonNumber = new(
|
|
309
|
+
@"\\A-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?\\z", RegexOptions.CultureInvariant);
|
|
310
|
+
|
|
311
|
+
${fields.join("\n")}
|
|
312
|
+
|
|
313
|
+
static BodyFormats()
|
|
314
|
+
{
|
|
315
|
+
${links.join("\n")}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
${controllers ? actionFilter([...shapes.keys()]) : endpointConvention}
|
|
319
|
+
/// <summary>The media type of the request as it was sent, without its parameters.</summary>
|
|
320
|
+
public static string? SentType(HttpRequest request)
|
|
321
|
+
{
|
|
322
|
+
var sent = request.HttpContext.Items[typeof(BodyShape)] as string ?? request.ContentType;
|
|
323
|
+
return sent?.Split(';')[0].Trim().ToLowerInvariant();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private static async Task ReadAsJson(HttpContext context, BodyShape shape, string[] types)
|
|
327
|
+
{
|
|
328
|
+
var request = context.Request;
|
|
329
|
+
context.Items[typeof(BodyShape)] = request.ContentType;
|
|
330
|
+
if (!global::Microsoft.Net.Http.Headers.MediaTypeHeaderValue.TryParse(
|
|
331
|
+
request.ContentType, out var sent))
|
|
332
|
+
{
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
var type = sent.MediaType.Value ?? "";
|
|
337
|
+
if (!types.Contains(type, StringComparer.OrdinalIgnoreCase))
|
|
338
|
+
{
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
JsonNode? body;
|
|
343
|
+
if (type.Equals(Form, StringComparison.OrdinalIgnoreCase))
|
|
344
|
+
{
|
|
345
|
+
body = await ReadForm(request, shape);
|
|
346
|
+
}
|
|
347
|
+
else if (type.EndsWith("/xml", StringComparison.OrdinalIgnoreCase)
|
|
348
|
+
|| type.EndsWith("+xml", StringComparison.OrdinalIgnoreCase))
|
|
349
|
+
{
|
|
350
|
+
body = await ReadXml(request, shape, sent.Encoding);
|
|
351
|
+
}
|
|
352
|
+
else
|
|
353
|
+
{
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// A body that was not sent stays empty, for the binder to judge.
|
|
358
|
+
var json = body is null ? Array.Empty<byte>() : Encoding.UTF8.GetBytes(body.ToJsonString());
|
|
359
|
+
var stream = new MemoryStream(json, writable: false);
|
|
360
|
+
context.Response.RegisterForDispose(stream);
|
|
361
|
+
request.Body = stream;
|
|
362
|
+
request.ContentLength = json.Length;
|
|
363
|
+
request.ContentType = "application/json; charset=utf-8";
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private static async Task<JsonNode?> ReadForm(HttpRequest request, BodyShape shape)
|
|
367
|
+
{
|
|
368
|
+
IFormCollection form;
|
|
369
|
+
try
|
|
370
|
+
{
|
|
371
|
+
form = await request.ReadFormAsync(request.HttpContext.RequestAborted);
|
|
372
|
+
}
|
|
373
|
+
catch (InvalidDataException exception)
|
|
374
|
+
{
|
|
375
|
+
throw new BadHttpRequestException("The form cannot be read.", 400, exception);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (form.Count == 0)
|
|
379
|
+
{
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
var found = new JsonObject();
|
|
384
|
+
foreach (var (name, values) in form)
|
|
385
|
+
{
|
|
386
|
+
var held = shape.Properties.TryGetValue(name, out var property)
|
|
387
|
+
? property.Shape
|
|
388
|
+
: shape.Extra;
|
|
389
|
+
if (held is null)
|
|
390
|
+
{
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Each item of a list repeats the name.
|
|
395
|
+
found[name] = held.Kind == BodyKind.Array || values.Count > 1
|
|
396
|
+
? new JsonArray(values.Select(
|
|
397
|
+
value => Field(value ?? "", held.Item ?? held)).ToArray())
|
|
398
|
+
: Field(values.ToString(), held);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
AddEmptyLists(found, shape);
|
|
402
|
+
return found;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// An object or dictionary inside a form is written as JSON, as OpenAPI says.
|
|
406
|
+
private static JsonNode? Field(string text, BodyShape shape)
|
|
407
|
+
{
|
|
408
|
+
if (shape.Kind is not (BodyKind.Object or BodyKind.Map or BodyKind.Array))
|
|
409
|
+
{
|
|
410
|
+
return Leaf(text, shape.Kind);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
try
|
|
414
|
+
{
|
|
415
|
+
return JsonNode.Parse(text);
|
|
416
|
+
}
|
|
417
|
+
catch (JsonException exception)
|
|
418
|
+
{
|
|
419
|
+
throw new BadHttpRequestException("A form value is not the JSON expected.", 400, exception);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
private static async Task<JsonNode?> ReadXml(HttpRequest request, BodyShape shape, Encoding? encoding)
|
|
424
|
+
{
|
|
425
|
+
using var buffer = new MemoryStream();
|
|
426
|
+
var chunk = new byte[81920];
|
|
427
|
+
int read;
|
|
428
|
+
while ((read = await request.Body.ReadAsync(chunk, request.HttpContext.RequestAborted)) > 0)
|
|
429
|
+
{
|
|
430
|
+
if (buffer.Length + read > MaxXmlBytes)
|
|
431
|
+
{
|
|
432
|
+
throw new BadHttpRequestException("The XML is too large.", 413);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
buffer.Write(chunk, 0, read);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (buffer.Length == 0)
|
|
439
|
+
{
|
|
440
|
+
return null;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// No document type, so that no entity can be expanded or fetched.
|
|
444
|
+
var settings = new XmlReaderSettings
|
|
445
|
+
{
|
|
446
|
+
DtdProcessing = DtdProcessing.Prohibit,
|
|
447
|
+
XmlResolver = null,
|
|
448
|
+
};
|
|
449
|
+
XmlReader Open()
|
|
450
|
+
{
|
|
451
|
+
var stream = new MemoryStream(buffer.GetBuffer(), 0, (int)buffer.Length, writable: false);
|
|
452
|
+
return encoding is null
|
|
453
|
+
? XmlReader.Create(stream, settings)
|
|
454
|
+
: XmlReader.Create(new StreamReader(stream, encoding), settings);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
XDocument document;
|
|
458
|
+
try
|
|
459
|
+
{
|
|
460
|
+
// Depth is checked before a tree is built, as reading a deep tree overflows the
|
|
461
|
+
// stack, which ends the process.
|
|
462
|
+
using (var depth = Open())
|
|
463
|
+
{
|
|
464
|
+
while (depth.Read())
|
|
465
|
+
{
|
|
466
|
+
if (depth.NodeType == XmlNodeType.Element && depth.Depth > MaxDepth)
|
|
467
|
+
{
|
|
468
|
+
throw new BadHttpRequestException("The XML is nested too deeply.", 400);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
using var reader = Open();
|
|
474
|
+
document = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
|
|
475
|
+
}
|
|
476
|
+
catch (XmlException exception)
|
|
477
|
+
{
|
|
478
|
+
throw new BadHttpRequestException("The XML cannot be read.", 400, exception);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
return Element(document.Root!, shape);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// The name of the outermost element is not read.
|
|
485
|
+
private static JsonNode? Element(XElement element, BodyShape shape)
|
|
486
|
+
{
|
|
487
|
+
var children = element.Elements().ToList();
|
|
488
|
+
var text = children.Count == 0 ? element.Value : "";
|
|
489
|
+
var empty = children.Count == 0 && string.IsNullOrWhiteSpace(text);
|
|
490
|
+
switch (shape.Kind)
|
|
491
|
+
{
|
|
492
|
+
case BodyKind.Array when children.Count > 0 || empty:
|
|
493
|
+
return new JsonArray(children.Select(
|
|
494
|
+
child => Element(child, shape.Item!)).ToArray());
|
|
495
|
+
case BodyKind.Object or BodyKind.Map when children.Count > 0 || empty:
|
|
496
|
+
return Members(children, shape);
|
|
497
|
+
case BodyKind.Any when children.Count > 0:
|
|
498
|
+
return Members(children, shape);
|
|
499
|
+
default:
|
|
500
|
+
// Elements where text belongs are given as an object, which is then refused.
|
|
501
|
+
return children.Count > 0 ? new JsonObject() : Leaf(text, shape.Kind);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
private static JsonObject Members(List<XElement> children, BodyShape shape)
|
|
506
|
+
{
|
|
507
|
+
var found = new JsonObject();
|
|
508
|
+
foreach (var named in children.GroupBy(child => child.Name.LocalName, StringComparer.Ordinal))
|
|
509
|
+
{
|
|
510
|
+
var held = shape.Properties.TryGetValue(named.Key, out var property)
|
|
511
|
+
? property.Shape
|
|
512
|
+
: shape.Extra ?? (shape.Kind == BodyKind.Any ? shape : null);
|
|
513
|
+
if (held is null)
|
|
514
|
+
{
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// Each item of a list is an element of the property's name.
|
|
519
|
+
if (held.Kind == BodyKind.Array || named.Count() > 1)
|
|
520
|
+
{
|
|
521
|
+
found[named.Key] = new JsonArray(named.Select(
|
|
522
|
+
child => Element(child, held.Item ?? held)).ToArray());
|
|
523
|
+
}
|
|
524
|
+
else
|
|
525
|
+
{
|
|
526
|
+
found[named.Key] = Element(named.First(), held);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
AddEmptyLists(found, shape);
|
|
531
|
+
return found;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// A list with no items writes nothing, so a required one that is missing is empty.
|
|
535
|
+
private static void AddEmptyLists(JsonObject found, BodyShape shape)
|
|
536
|
+
{
|
|
537
|
+
foreach (var (name, property) in shape.Properties)
|
|
538
|
+
{
|
|
539
|
+
if (property.Required && property.Shape.Kind == BodyKind.Array && !found.ContainsKey(name))
|
|
540
|
+
{
|
|
541
|
+
found[name] = new JsonArray();
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Text that is not the value expected stays text, for the JSON reader to refuse.
|
|
547
|
+
private static JsonNode? Leaf(string text, BodyKind kind)
|
|
548
|
+
{
|
|
549
|
+
var trimmed = text.Trim();
|
|
550
|
+
if (kind == BodyKind.Boolean && trimmed is "true" or "false")
|
|
551
|
+
{
|
|
552
|
+
return JsonValue.Create(trimmed == "true");
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return kind == BodyKind.Number && JsonNumber.IsMatch(trimmed)
|
|
556
|
+
? JsonNode.Parse(trimmed)
|
|
557
|
+
: JsonValue.Create(text);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
`;
|
|
561
|
+
}
|
|
@@ -413,14 +413,67 @@ public sealed class AdditionalValues<T>(
|
|
|
413
413
|
global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
|
|
414
414
|
}
|
|
415
415
|
|
|
416
|
-
/// <summary>
|
|
417
|
-
|
|
416
|
+
/// <summary>
|
|
417
|
+
/// Enums written as their names. Only a declared name is read, exactly as written: numbers, lists
|
|
418
|
+
/// such as "a,b" and padded names are refused.
|
|
419
|
+
/// </summary>
|
|
420
|
+
public sealed class StringEnumConverter<TEnum> : JsonConverter<TEnum>
|
|
418
421
|
where TEnum : struct, Enum
|
|
419
422
|
{
|
|
420
|
-
|
|
421
|
-
|
|
423
|
+
private static readonly (string Name, TEnum Value)[] Members =
|
|
424
|
+
Array.ConvertAll(Enum.GetNames<TEnum>(), member =>
|
|
425
|
+
{
|
|
426
|
+
var written = typeof(TEnum).GetField(member)!
|
|
427
|
+
.GetCustomAttributes(typeof(JsonStringEnumMemberNameAttribute), false);
|
|
428
|
+
var name = written.Length > 0 ? ((JsonStringEnumMemberNameAttribute)written[0]).Name : member;
|
|
429
|
+
return (name, Enum.Parse<TEnum>(member));
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
/// <summary>The declared names.</summary>
|
|
433
|
+
internal static IEnumerable<string> Names => Array.ConvertAll(Members, member => member.Name);
|
|
434
|
+
|
|
435
|
+
public override TEnum Read(
|
|
436
|
+
ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
|
|
437
|
+
reader.TokenType == JsonTokenType.String ? Value(reader.GetString()!) : throw Unexpected();
|
|
438
|
+
|
|
439
|
+
public override TEnum ReadAsPropertyName(
|
|
440
|
+
ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
|
|
441
|
+
Value(reader.GetString()!);
|
|
442
|
+
|
|
443
|
+
public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) =>
|
|
444
|
+
writer.WriteStringValue(Name(value));
|
|
445
|
+
|
|
446
|
+
public override void WriteAsPropertyName(
|
|
447
|
+
Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) =>
|
|
448
|
+
writer.WritePropertyName(Name(value));
|
|
449
|
+
|
|
450
|
+
private static TEnum Value(string text)
|
|
451
|
+
{
|
|
452
|
+
foreach (var member in Members)
|
|
453
|
+
{
|
|
454
|
+
if (string.Equals(member.Name, text, StringComparison.Ordinal))
|
|
455
|
+
{
|
|
456
|
+
return member.Value;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
throw Unexpected();
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private static string Name(TEnum value)
|
|
422
464
|
{
|
|
465
|
+
foreach (var member in Members)
|
|
466
|
+
{
|
|
467
|
+
if (EqualityComparer<TEnum>.Default.Equals(member.Value, value))
|
|
468
|
+
{
|
|
469
|
+
return member.Name;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
throw new JsonException($"Not a value of {typeof(TEnum).Name}.");
|
|
423
474
|
}
|
|
475
|
+
|
|
476
|
+
private static JsonException Unexpected() => new($"Expected a value of {typeof(TEnum).Name}.");
|
|
424
477
|
}
|
|
425
478
|
|
|
426
479
|
/// <summary>Enums written as numbers. Undeclared numbers are refused.</summary>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ApiModel } from "../../model/types.js";
|
|
2
|
+
import type { ServiceContract } from "./services.js";
|
|
3
|
+
import type { Binding } from "./binding.js";
|
|
4
|
+
/** What is said of one operation. */
|
|
5
|
+
export interface Documentation {
|
|
6
|
+
name: string;
|
|
7
|
+
summary?: string;
|
|
8
|
+
description?: string;
|
|
9
|
+
/** Metadata declaring responses, which MVC reads from attributes instead. */
|
|
10
|
+
produces: string[];
|
|
11
|
+
/** The `DocumentedOperation` read by the generated transformer, when OpenAPI is on. */
|
|
12
|
+
operation?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function documentationWriter(model: ApiModel, rootNamespace: string, openapi: boolean,
|
|
15
|
+
/** MVC lists more content types for a body than the action takes. */
|
|
16
|
+
controllers?: boolean): (group: string, contract: ServiceContract["operations"][number], binding: Binding,
|
|
17
|
+
/** True when a content type tells this operation from others of its route. */
|
|
18
|
+
sharesBody?: boolean) => Documentation;
|