sheridan-typespec-aspnet 0.2.1 → 0.3.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 +10 -3
- package/dist/src/emitter.js +70 -2
- package/dist/src/lib.d.ts +32 -2
- package/dist/src/lib.js +12 -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 +39 -3
- package/dist/src/model/types.d.ts +10 -0
- package/dist/src/naming/names.js +11 -1
- package/dist/src/naming/services.d.ts +10 -0
- package/dist/src/naming/services.js +11 -2
- package/dist/src/render/minimal/documentation.d.ts +4 -0
- package/dist/src/render/minimal/documentation.js +107 -0
- package/dist/src/render/minimal/endpoints.d.ts +14 -0
- package/dist/src/render/minimal/endpoints.js +139 -0
- package/dist/src/render/minimal/results.d.ts +11 -0
- package/dist/src/render/minimal/results.js +145 -0
- package/dist/src/render/shared/api-setup.d.ts +6 -1
- package/dist/src/render/shared/api-setup.js +131 -11
- package/dist/src/render/shared/binding.d.ts +33 -0
- package/dist/src/render/shared/binding.js +395 -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 +248 -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 +86 -0
- package/dist/src/render/shared/routes.d.ts +37 -0
- package/dist/src/render/shared/routes.js +241 -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,248 @@
|
|
|
1
|
+
// What ASP.NET Core cannot read from a handler is told to OpenAPI through endpoint metadata, which
|
|
2
|
+
// a generated transformer applies.
|
|
3
|
+
export function renderOpenApi(rootNamespace) {
|
|
4
|
+
return `// <auto-generated/>
|
|
5
|
+
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
6
|
+
#nullable enable
|
|
7
|
+
|
|
8
|
+
namespace ${rootNamespace}.Documentation;
|
|
9
|
+
|
|
10
|
+
// Inside the namespace, so that a type in the spec cannot hide these.
|
|
11
|
+
using global::System;
|
|
12
|
+
using global::System.Collections.Generic;
|
|
13
|
+
using global::System.ComponentModel.DataAnnotations;
|
|
14
|
+
using global::System.Linq;
|
|
15
|
+
using global::System.Net.Http;
|
|
16
|
+
using global::System.Text.Json.Serialization;
|
|
17
|
+
using global::System.Reflection;
|
|
18
|
+
using global::System.Threading;
|
|
19
|
+
using global::System.Threading.Tasks;
|
|
20
|
+
using global::Microsoft.AspNetCore.OpenApi;
|
|
21
|
+
using global::Microsoft.Extensions.DependencyInjection;
|
|
22
|
+
using global::Microsoft.OpenApi;
|
|
23
|
+
using global::${rootNamespace}.Validation;
|
|
24
|
+
|
|
25
|
+
/// <summary>A value of a request, described where the handler does not say it all.</summary>
|
|
26
|
+
internal sealed record DocumentedParameter(
|
|
27
|
+
string Name,
|
|
28
|
+
string In,
|
|
29
|
+
Type? Type = null,
|
|
30
|
+
bool Required = false,
|
|
31
|
+
ValidationAttribute[]? Constraints = null);
|
|
32
|
+
|
|
33
|
+
internal sealed record DocumentedHeader(string Name, Type Type, bool Required);
|
|
34
|
+
|
|
35
|
+
/// <summary>A response of the spec, keyed by its status, such as "200", "4XX" or "default".</summary>
|
|
36
|
+
internal sealed record DocumentedResponse(
|
|
37
|
+
string Status,
|
|
38
|
+
Type? Body = null,
|
|
39
|
+
string? ContentType = null,
|
|
40
|
+
DocumentedHeader[]? Headers = null);
|
|
41
|
+
|
|
42
|
+
/// <summary>What the spec says of an operation, beyond what its handler shows.</summary>
|
|
43
|
+
internal sealed record DocumentedOperation(
|
|
44
|
+
DocumentedResponse[] Responses,
|
|
45
|
+
DocumentedParameter[]? Parameters = null,
|
|
46
|
+
DocumentedResponse? Request = null,
|
|
47
|
+
bool Deprecated = false,
|
|
48
|
+
string[]? SentAs = null);
|
|
49
|
+
|
|
50
|
+
internal static class OpenApiSetup
|
|
51
|
+
{
|
|
52
|
+
public static IServiceCollection AddGeneratedOpenApi(IServiceCollection services) =>
|
|
53
|
+
services.AddOpenApi(options =>
|
|
54
|
+
{
|
|
55
|
+
options.AddOperationTransformer(Describe);
|
|
56
|
+
options.AddSchemaTransformer(Constrain);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
private static async Task Describe(
|
|
60
|
+
OpenApiOperation operation,
|
|
61
|
+
OpenApiOperationTransformerContext context,
|
|
62
|
+
CancellationToken cancellationToken)
|
|
63
|
+
{
|
|
64
|
+
var found = context.Description.ActionDescriptor.EndpointMetadata
|
|
65
|
+
.OfType<DocumentedOperation>()
|
|
66
|
+
.LastOrDefault();
|
|
67
|
+
if (found is null)
|
|
68
|
+
{
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (found.Deprecated)
|
|
73
|
+
{
|
|
74
|
+
operation.Deprecated = true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async Task<OpenApiSchema> Schema(Type type) =>
|
|
78
|
+
await context.GetOrCreateSchemaAsync(type, cancellationToken: cancellationToken);
|
|
79
|
+
|
|
80
|
+
foreach (var described in found.Parameters ?? [])
|
|
81
|
+
{
|
|
82
|
+
var location = Enum.Parse<ParameterLocation>(described.In, true);
|
|
83
|
+
operation.Parameters ??= new List<IOpenApiParameter>();
|
|
84
|
+
var parameter = operation.Parameters.OfType<OpenApiParameter>().FirstOrDefault(
|
|
85
|
+
p => p.In == location
|
|
86
|
+
&& string.Equals(p.Name, described.Name, StringComparison.OrdinalIgnoreCase));
|
|
87
|
+
if (parameter is null)
|
|
88
|
+
{
|
|
89
|
+
parameter = new OpenApiParameter
|
|
90
|
+
{
|
|
91
|
+
Name = described.Name,
|
|
92
|
+
In = location,
|
|
93
|
+
Required = described.Required,
|
|
94
|
+
};
|
|
95
|
+
operation.Parameters.Add(parameter);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (described.Type is not null)
|
|
99
|
+
{
|
|
100
|
+
parameter.Schema = await Schema(described.Type);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (parameter.Schema is OpenApiSchema schema)
|
|
104
|
+
{
|
|
105
|
+
Apply(schema, described.Constraints ?? []);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (found.Request is { Body: { } sent } request)
|
|
110
|
+
{
|
|
111
|
+
operation.RequestBody = new OpenApiRequestBody
|
|
112
|
+
{
|
|
113
|
+
Required = true,
|
|
114
|
+
Content = new Dictionary<string, IOpenApiMediaType>
|
|
115
|
+
{
|
|
116
|
+
[request.ContentType!] = new OpenApiMediaType { Schema = await Schema(sent) },
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (found.SentAs is { } types
|
|
122
|
+
&& operation.RequestBody is OpenApiRequestBody { Content: { Count: 1 } content } bound)
|
|
123
|
+
{
|
|
124
|
+
var only = content.Values.First();
|
|
125
|
+
bound.Content = types.ToDictionary(type => type, _ => only);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
var responses = new OpenApiResponses();
|
|
129
|
+
foreach (var described in found.Responses)
|
|
130
|
+
{
|
|
131
|
+
// What ASP.NET Core described is kept, and the rest added.
|
|
132
|
+
var response = operation.Responses?.GetValueOrDefault(described.Status) as OpenApiResponse;
|
|
133
|
+
if (response is null)
|
|
134
|
+
{
|
|
135
|
+
response = new OpenApiResponse { Description = described.Status };
|
|
136
|
+
if (described.Body is not null)
|
|
137
|
+
{
|
|
138
|
+
response.Content = new Dictionary<string, IOpenApiMediaType>
|
|
139
|
+
{
|
|
140
|
+
[described.ContentType!] = new OpenApiMediaType { Schema = await Schema(described.Body) },
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
foreach (var header in described.Headers ?? [])
|
|
146
|
+
{
|
|
147
|
+
response.Headers ??= new Dictionary<string, IOpenApiHeader>();
|
|
148
|
+
response.Headers[header.Name] = new OpenApiHeader
|
|
149
|
+
{
|
|
150
|
+
Required = header.Required,
|
|
151
|
+
Schema = await Schema(header.Type),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
responses[described.Status] = response;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
operation.Responses = responses;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private static async Task Constrain(
|
|
162
|
+
OpenApiSchema schema,
|
|
163
|
+
OpenApiSchemaTransformerContext context,
|
|
164
|
+
CancellationToken cancellationToken)
|
|
165
|
+
{
|
|
166
|
+
// A merge-patch property is described as the value it may hold.
|
|
167
|
+
var held = context.JsonTypeInfo.Type;
|
|
168
|
+
if (held.IsGenericType && held.Namespace == typeof(global::${rootNamespace}.Serialization.JsonSetup).Namespace
|
|
169
|
+
&& held.Name is "Optional\`1" or "OptionalNullable\`1")
|
|
170
|
+
{
|
|
171
|
+
var inner = await context.GetOrCreateSchemaAsync(
|
|
172
|
+
held.GetGenericArguments()[0], cancellationToken: cancellationToken);
|
|
173
|
+
schema.Type = inner.Type;
|
|
174
|
+
schema.Format = inner.Format;
|
|
175
|
+
schema.Items = inner.Items;
|
|
176
|
+
schema.Properties = inner.Properties;
|
|
177
|
+
schema.Required = inner.Required;
|
|
178
|
+
schema.Enum = inner.Enum;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
var attributes = context.JsonPropertyInfo?.AttributeProvider?
|
|
182
|
+
.GetCustomAttributes(typeof(ValidationAttribute), true);
|
|
183
|
+
if (attributes is not null)
|
|
184
|
+
{
|
|
185
|
+
Apply(schema, attributes.OfType<ValidationAttribute>());
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
var converter = context.JsonPropertyInfo?.AttributeProvider?
|
|
189
|
+
.GetCustomAttributes(typeof(JsonConverterAttribute), true)
|
|
190
|
+
.OfType<JsonConverterAttribute>()
|
|
191
|
+
.FirstOrDefault()?.ConverterType?.Name;
|
|
192
|
+
// A converter of an encoding hides the type from OpenAPI.
|
|
193
|
+
if (schema.Type is null && converter is not null && Encoded(converter) is { } encoded)
|
|
194
|
+
{
|
|
195
|
+
schema.Type = encoded.Type;
|
|
196
|
+
schema.Format = encoded.Format;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private static (JsonSchemaType Type, string Format)? Encoded(string converter) => converter switch
|
|
202
|
+
{
|
|
203
|
+
"UtcDateTimeConverter" or "OffsetDateTimeConverter" => (JsonSchemaType.String, "date-time"),
|
|
204
|
+
"Rfc7231DateTimeConverter" => (JsonSchemaType.String, "http-date"),
|
|
205
|
+
"UnixTimestampConverter" or "UnixTimestamp32Converter" => (JsonSchemaType.Integer, "unixtime"),
|
|
206
|
+
"Iso8601DurationConverter" => (JsonSchemaType.String, "duration"),
|
|
207
|
+
"SecondsDurationConverter" or "MillisecondsDurationConverter" => (JsonSchemaType.Number, "double"),
|
|
208
|
+
"WholeSecondsDurationConverter" or "WholeMillisecondsDurationConverter" => (JsonSchemaType.Integer, "int64"),
|
|
209
|
+
"Base64UrlConverter" => (JsonSchemaType.String, "base64url"),
|
|
210
|
+
"StringBooleanConverter" => (JsonSchemaType.String, "boolean"),
|
|
211
|
+
_ => null,
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
private static void Apply(OpenApiSchema schema, IEnumerable<ValidationAttribute> attributes)
|
|
215
|
+
{
|
|
216
|
+
foreach (var attribute in attributes)
|
|
217
|
+
{
|
|
218
|
+
switch (attribute)
|
|
219
|
+
{
|
|
220
|
+
case TextLengthAttribute text:
|
|
221
|
+
schema.MinLength = text.Minimum > 0 ? text.Minimum : null;
|
|
222
|
+
schema.MaxLength = text.Maximum < int.MaxValue ? text.Maximum : null;
|
|
223
|
+
break;
|
|
224
|
+
case PatternAttribute pattern:
|
|
225
|
+
schema.Pattern = pattern.Source ?? pattern.Expression;
|
|
226
|
+
break;
|
|
227
|
+
case UuidAttribute:
|
|
228
|
+
schema.Format = "uuid";
|
|
229
|
+
break;
|
|
230
|
+
case global::${rootNamespace}.Validation.EmailAttribute:
|
|
231
|
+
schema.Format = "email";
|
|
232
|
+
break;
|
|
233
|
+
case ItemCountAttribute items:
|
|
234
|
+
schema.MinItems = items.Minimum > 0 ? items.Minimum : null;
|
|
235
|
+
schema.MaxItems = items.Maximum < int.MaxValue ? items.Maximum : null;
|
|
236
|
+
break;
|
|
237
|
+
case NumberRangeAttribute range:
|
|
238
|
+
schema.Minimum = range.Minimum ?? schema.Minimum;
|
|
239
|
+
schema.Maximum = range.Maximum ?? schema.Maximum;
|
|
240
|
+
schema.ExclusiveMinimum = range.ExclusiveMinimum;
|
|
241
|
+
schema.ExclusiveMaximum = range.ExclusiveMaximum;
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
`;
|
|
248
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// The generated helpers that read request values ASP.NET Core does not read as the spec writes them.
|
|
2
|
+
export function renderParameters(rootNamespace) {
|
|
3
|
+
return `// <auto-generated/>
|
|
4
|
+
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
5
|
+
#nullable enable
|
|
6
|
+
|
|
7
|
+
namespace ${rootNamespace}.Requests;
|
|
8
|
+
|
|
9
|
+
// Inside the namespace, so that a type in the spec cannot hide these.
|
|
10
|
+
using global::System;
|
|
11
|
+
using global::System.Collections.Generic;
|
|
12
|
+
using global::System.ComponentModel.DataAnnotations;
|
|
13
|
+
using global::System.Linq;
|
|
14
|
+
using global::System.IO;
|
|
15
|
+
using global::System.Text;
|
|
16
|
+
using global::System.Text.Json;
|
|
17
|
+
using global::System.Text.Json.Serialization;
|
|
18
|
+
using global::System.Threading;
|
|
19
|
+
using global::System.Threading.Tasks;
|
|
20
|
+
using global::Microsoft.AspNetCore.Http;
|
|
21
|
+
|
|
22
|
+
/// <summary>A value of a request that breaks a constraint of the spec.</summary>
|
|
23
|
+
internal sealed class RequestInvalidException(string name, string message) : Exception(message)
|
|
24
|
+
{
|
|
25
|
+
public string Name { get; } = name;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// <summary>Reads values of a request. What cannot be read is answered with 400.</summary>
|
|
29
|
+
internal static class Parameters
|
|
30
|
+
{
|
|
31
|
+
private static readonly JsonSerializerOptions Options = Create(null);
|
|
32
|
+
|
|
33
|
+
/// <summary>Reads text as the JSON of the type is read: a number as it is, else a string.</summary>
|
|
34
|
+
public static T Value<T>(string text, bool number, string name) =>
|
|
35
|
+
Read<T>(text, number, name, Options);
|
|
36
|
+
|
|
37
|
+
/// <summary>Reads text with the converter of an encoding.</summary>
|
|
38
|
+
public static T Value<T, TConverter>(string text, bool number, string name)
|
|
39
|
+
where TConverter : JsonConverter, new() =>
|
|
40
|
+
Read<T>(text, number, name, Converted<TConverter>.Options);
|
|
41
|
+
|
|
42
|
+
/// <summary>Reads a value from text already at hand.</summary>
|
|
43
|
+
public static T With<T>(string text, Converter<string, T> read) => read(text);
|
|
44
|
+
|
|
45
|
+
public static T[] List<T>(string[] items, Converter<string, T> read) =>
|
|
46
|
+
Array.ConvertAll(items, read);
|
|
47
|
+
|
|
48
|
+
/// <summary>The items of a list written as one value, separated by commas.</summary>
|
|
49
|
+
public static string[] Split(string text, bool trim) =>
|
|
50
|
+
text.Length == 0
|
|
51
|
+
? []
|
|
52
|
+
: text.Split(',', trim ? StringSplitOptions.TrimEntries : StringSplitOptions.None);
|
|
53
|
+
|
|
54
|
+
/// <summary>The items of a list of HTTP dates, each of which holds one comma.</summary>
|
|
55
|
+
public static string[] SplitDates(string text)
|
|
56
|
+
{
|
|
57
|
+
var parts = Split(text, false);
|
|
58
|
+
var dates = new string[(parts.Length + 1) / 2];
|
|
59
|
+
for (var index = 0; index < dates.Length; index++)
|
|
60
|
+
{
|
|
61
|
+
var first = index * 2;
|
|
62
|
+
dates[index] = first + 1 < parts.Length
|
|
63
|
+
? $"{parts[first]},{parts[first + 1]}".Trim()
|
|
64
|
+
: parts[first];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return dates;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// <summary>The text of a value as JSON writes it, or null for none.</summary>
|
|
71
|
+
public static string? Write<T>(T value) => Text(value, Options);
|
|
72
|
+
|
|
73
|
+
/// <summary>The text of a value written with the converter of an encoding.</summary>
|
|
74
|
+
public static string? Write<T, TConverter>(T value)
|
|
75
|
+
where TConverter : JsonConverter, new() =>
|
|
76
|
+
Text(value, Converted<TConverter>.Options);
|
|
77
|
+
|
|
78
|
+
/// <summary>A list written as one value, separated by commas.</summary>
|
|
79
|
+
public static string? Join(IEnumerable<string?>? items) =>
|
|
80
|
+
items is null ? null : string.Join(", ", items.Where(item => item is not null));
|
|
81
|
+
|
|
82
|
+
public static string? Join<T>(IEnumerable<T>? items, Func<T, string?> write) =>
|
|
83
|
+
items is null ? null : Join(items.Select(write));
|
|
84
|
+
|
|
85
|
+
private static string? Text<T>(T value, JsonSerializerOptions options)
|
|
86
|
+
{
|
|
87
|
+
var json = JsonSerializer.Serialize(value, options);
|
|
88
|
+
return json.StartsWith('"')
|
|
89
|
+
? JsonSerializer.Deserialize<string>(json)
|
|
90
|
+
: json == "null" ? null : json;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// <summary>Returns a value that meets every constraint on it. An absent value does.</summary>
|
|
94
|
+
public static T Check<T>(T value, string name, params ValidationAttribute[] constraints)
|
|
95
|
+
{
|
|
96
|
+
foreach (var constraint in constraints)
|
|
97
|
+
{
|
|
98
|
+
if (!constraint.IsValid(value))
|
|
99
|
+
{
|
|
100
|
+
throw new RequestInvalidException(name, constraint.FormatErrorMessage(name));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
public static string Required(string? text, string name) =>
|
|
108
|
+
text ?? throw new BadHttpRequestException($"The value \\"{name}\\" is required.");
|
|
109
|
+
|
|
110
|
+
/// <summary>The body as text, or null when none was sent and none is required.</summary>
|
|
111
|
+
public static async Task<string> Text(HttpRequest request, bool optional, CancellationToken cancellationToken)
|
|
112
|
+
{
|
|
113
|
+
var bytes = await Bytes(request, optional, cancellationToken);
|
|
114
|
+
if (bytes is null)
|
|
115
|
+
{
|
|
116
|
+
return null!;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
var charset = request.GetTypedHeaders().ContentType?.Encoding;
|
|
120
|
+
using var reader = new StreamReader(new MemoryStream(bytes), charset ?? Encoding.UTF8);
|
|
121
|
+
return await reader.ReadToEndAsync(cancellationToken);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// <summary>The body as bytes, or null when none was sent and none is required.</summary>
|
|
125
|
+
public static async Task<byte[]> Bytes(HttpRequest request, bool optional, CancellationToken cancellationToken)
|
|
126
|
+
{
|
|
127
|
+
using var buffer = new MemoryStream();
|
|
128
|
+
await request.Body.CopyToAsync(buffer, cancellationToken);
|
|
129
|
+
return optional && buffer.Length == 0 && request.ContentType is null ? null! : buffer.ToArray();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private static T Read<T>(string text, bool number, string name, JsonSerializerOptions options)
|
|
133
|
+
{
|
|
134
|
+
try
|
|
135
|
+
{
|
|
136
|
+
var json = number ? text : JsonSerializer.Serialize(text);
|
|
137
|
+
if (JsonSerializer.Deserialize<T>(json, options) is { } value)
|
|
138
|
+
{
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
catch (Exception error) when (error is JsonException or FormatException
|
|
143
|
+
or InvalidOperationException or ArgumentException or NotSupportedException or OverflowException)
|
|
144
|
+
{
|
|
145
|
+
throw new BadHttpRequestException($"The value \\"{name}\\" is not valid.", error);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
throw new BadHttpRequestException($"The value \\"{name}\\" is not valid.");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private static JsonSerializerOptions Create(JsonConverter? converter)
|
|
152
|
+
{
|
|
153
|
+
var options = new JsonSerializerOptions();
|
|
154
|
+
global::${rootNamespace}.Serialization.JsonSetup.Configure(options);
|
|
155
|
+
if (converter is not null)
|
|
156
|
+
{
|
|
157
|
+
options.Converters.Add(converter);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return options;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private static class Converted<TConverter>
|
|
164
|
+
where TConverter : JsonConverter, new()
|
|
165
|
+
{
|
|
166
|
+
public static readonly JsonSerializerOptions Options = Create(new TConverter());
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
`;
|
|
170
|
+
}
|
|
171
|
+
/** The generated helpers that send what ASP.NET Core's results do not. */
|
|
172
|
+
export function renderResponses(rootNamespace) {
|
|
173
|
+
return `// <auto-generated/>
|
|
174
|
+
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
175
|
+
#nullable enable
|
|
176
|
+
|
|
177
|
+
namespace ${rootNamespace}.Responses;
|
|
178
|
+
|
|
179
|
+
// Inside the namespace, so that a type in the spec cannot hide these.
|
|
180
|
+
using global::System.Threading.Tasks;
|
|
181
|
+
using global::Microsoft.AspNetCore.Http;
|
|
182
|
+
|
|
183
|
+
/// <summary>Adds a declared header to a result.</summary>
|
|
184
|
+
public static class ResponseHeaders
|
|
185
|
+
{
|
|
186
|
+
/// <summary>Sets a header, unless it has no value, and returns the result.</summary>
|
|
187
|
+
public static TResult With<TResult>(TResult result, HttpContext context, string name, string? value)
|
|
188
|
+
{
|
|
189
|
+
if (value is not null)
|
|
190
|
+
{
|
|
191
|
+
context.Response.Headers[name] = value;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return result;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/// <summary>A body of bytes with any status.</summary>
|
|
199
|
+
public sealed class BytesHttpResult(int statusCode, byte[]? body, string contentType)
|
|
200
|
+
: IResult, IStatusCodeHttpResult, IContentTypeHttpResult
|
|
201
|
+
{
|
|
202
|
+
public int StatusCode { get; } = statusCode;
|
|
203
|
+
|
|
204
|
+
int? IStatusCodeHttpResult.StatusCode => StatusCode;
|
|
205
|
+
|
|
206
|
+
public byte[]? Body { get; } = body;
|
|
207
|
+
|
|
208
|
+
public string ContentType { get; } = contentType;
|
|
209
|
+
|
|
210
|
+
public async Task ExecuteAsync(HttpContext httpContext)
|
|
211
|
+
{
|
|
212
|
+
httpContext.Response.StatusCode = StatusCode;
|
|
213
|
+
if (Body is null)
|
|
214
|
+
{
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
httpContext.Response.ContentType = ContentType;
|
|
219
|
+
httpContext.Response.ContentLength = Body.Length;
|
|
220
|
+
await httpContext.Response.Body.WriteAsync(Body, httpContext.RequestAborted);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
`;
|
|
224
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** True when C# holds the type by reference, so that `?` does not make another type of it. */
|
|
2
|
+
export function isReference(model, ref) {
|
|
3
|
+
if (ref.kind === "nullable")
|
|
4
|
+
return isReference(model, ref.type);
|
|
5
|
+
if (ref.kind === "array" || ref.kind === "record")
|
|
6
|
+
return true;
|
|
7
|
+
if (ref.kind === "literal")
|
|
8
|
+
return typeof ref.value === "string";
|
|
9
|
+
const builtinReference = (name) => ["string", "bytes", "url"].includes(name ?? "");
|
|
10
|
+
if (ref.kind === "scalar")
|
|
11
|
+
return builtinReference(ref.name);
|
|
12
|
+
if (ref.kind !== "named")
|
|
13
|
+
return false;
|
|
14
|
+
const declared = model.types.get(ref.id);
|
|
15
|
+
if (declared.kind === "scalar")
|
|
16
|
+
return builtinReference(declared.builtin);
|
|
17
|
+
return declared.kind === "model";
|
|
18
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function renderRequestSelector(rootNamespace: string): string;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Chooses between operations that share a verb and route, in either style.
|
|
2
|
+
import { csharpFile } from "./writer.js";
|
|
3
|
+
export function renderRequestSelector(rootNamespace) {
|
|
4
|
+
return csharpFile(`${rootNamespace}.Routing`, `// Inside the namespace, so that a type of the spec named alike does not hide these.
|
|
5
|
+
using global::Microsoft.AspNetCore.Http;
|
|
6
|
+
using global::Microsoft.AspNetCore.Routing;
|
|
7
|
+
using global::Microsoft.AspNetCore.Routing.Matching;
|
|
8
|
+
|
|
9
|
+
/// <summary>A query value or header a request must carry.</summary>
|
|
10
|
+
internal sealed record RequiredValue(bool Header, string Name, string Value, bool IgnoreCase)
|
|
11
|
+
{
|
|
12
|
+
public bool IsIn(HttpRequest request)
|
|
13
|
+
{
|
|
14
|
+
var found = Header ? request.Headers[Name] : request.Query[Name];
|
|
15
|
+
var comparison = IgnoreCase
|
|
16
|
+
? global::System.StringComparison.OrdinalIgnoreCase
|
|
17
|
+
: global::System.StringComparison.Ordinal;
|
|
18
|
+
return found.Count == 1 && string.Equals(found[0], Value, comparison);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/// <summary>What a request must carry to reach one of the operations sharing a route.</summary>
|
|
23
|
+
internal sealed record RequestCondition(RequiredValue[] Values, string[] ContentTypes)
|
|
24
|
+
{
|
|
25
|
+
public bool IsMetBy(HttpRequest request)
|
|
26
|
+
{
|
|
27
|
+
foreach (var value in Values)
|
|
28
|
+
{
|
|
29
|
+
if (!value.IsIn(request))
|
|
30
|
+
{
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (ContentTypes.Length == 0)
|
|
36
|
+
{
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
var sent = request.ContentType?.Split(';')[0].Trim();
|
|
41
|
+
foreach (var type in ContentTypes)
|
|
42
|
+
{
|
|
43
|
+
if (string.Equals(type, sent, global::System.StringComparison.OrdinalIgnoreCase))
|
|
44
|
+
{
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// <summary>Leaves only the operations whose condition a request meets.</summary>
|
|
54
|
+
internal sealed class RequestSelector : MatcherPolicy, IEndpointSelectorPolicy
|
|
55
|
+
{
|
|
56
|
+
public override int Order => 0;
|
|
57
|
+
|
|
58
|
+
public bool AppliesToEndpoints(global::System.Collections.Generic.IReadOnlyList<Endpoint> endpoints)
|
|
59
|
+
{
|
|
60
|
+
foreach (var endpoint in endpoints)
|
|
61
|
+
{
|
|
62
|
+
if (endpoint.Metadata.GetMetadata<RequestCondition>() is not null)
|
|
63
|
+
{
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
public global::System.Threading.Tasks.Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
|
|
72
|
+
{
|
|
73
|
+
for (var index = 0; index < candidates.Count; index++)
|
|
74
|
+
{
|
|
75
|
+
if (candidates.IsValidCandidate(index)
|
|
76
|
+
&& candidates[index].Endpoint.Metadata.GetMetadata<RequestCondition>() is { } condition
|
|
77
|
+
&& !condition.IsMetBy(httpContext.Request))
|
|
78
|
+
{
|
|
79
|
+
candidates.SetValidity(index, false);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return global::System.Threading.Tasks.Task.CompletedTask;
|
|
84
|
+
}
|
|
85
|
+
}`);
|
|
86
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Program } from "@typespec/compiler";
|
|
2
|
+
import type { ApiModel, OperationModel } from "../../model/types.js";
|
|
3
|
+
export interface Segment {
|
|
4
|
+
/** As written in an ASP.NET Core route template. */
|
|
5
|
+
text: string;
|
|
6
|
+
/** True for an optional parameter or a catch-all, which only the end of a route can hold. */
|
|
7
|
+
trailing: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface Route {
|
|
10
|
+
segments: Segment[];
|
|
11
|
+
/** Query values written into the route, such as `?kind=a`. */
|
|
12
|
+
query: [name: string, value: string][];
|
|
13
|
+
}
|
|
14
|
+
/** A value a request must carry to reach an operation. */
|
|
15
|
+
export interface RequiredValue {
|
|
16
|
+
in: "query" | "header";
|
|
17
|
+
name: string;
|
|
18
|
+
value: string;
|
|
19
|
+
ignoreCase: boolean;
|
|
20
|
+
}
|
|
21
|
+
/** What tells an operation apart from the others of its verb and route. */
|
|
22
|
+
export interface Condition {
|
|
23
|
+
values: RequiredValue[];
|
|
24
|
+
/** Empty when the content type does not matter. */
|
|
25
|
+
contentTypes: string[];
|
|
26
|
+
/** The content types of every operation told apart by one, this one included. */
|
|
27
|
+
accepted: string[];
|
|
28
|
+
}
|
|
29
|
+
/** Reads the URI template of an operation. Returns what is wrong when ASP.NET Core cannot map it. */
|
|
30
|
+
export declare function parseRoute(operation: OperationModel): Route | string;
|
|
31
|
+
export interface Routing {
|
|
32
|
+
routes: Map<OperationModel, Route>;
|
|
33
|
+
/** For operations sharing a verb and route. */
|
|
34
|
+
conditions: Map<OperationModel, Condition>;
|
|
35
|
+
}
|
|
36
|
+
/** Reads every route, and works out how requests reach operations that share one. */
|
|
37
|
+
export declare function planRoutes(program: Program, model: ApiModel): Routing;
|