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.
Files changed (36) hide show
  1. package/README.md +4 -4
  2. package/dist/src/emitter.js +72 -41
  3. package/dist/src/lib.d.ts +17 -2
  4. package/dist/src/lib.js +6 -0
  5. package/dist/src/model/collect.js +18 -4
  6. package/dist/src/model/types.d.ts +2 -0
  7. package/dist/src/naming/names.d.ts +1 -1
  8. package/dist/src/naming/names.js +2 -2
  9. package/dist/src/naming/services.d.ts +3 -3
  10. package/dist/src/naming/services.js +9 -3
  11. package/dist/src/render/controllers/controllers.d.ts +20 -0
  12. package/dist/src/render/controllers/controllers.js +559 -0
  13. package/dist/src/render/controllers/results.d.ts +10 -0
  14. package/dist/src/render/controllers/results.js +82 -0
  15. package/dist/src/render/minimal/endpoints.d.ts +2 -2
  16. package/dist/src/render/minimal/endpoints.js +23 -1
  17. package/dist/src/render/minimal/results.js +33 -88
  18. package/dist/src/render/shared/api-setup.d.ts +4 -1
  19. package/dist/src/render/shared/api-setup.js +58 -24
  20. package/dist/src/render/shared/binding.d.ts +11 -1
  21. package/dist/src/render/shared/binding.js +52 -21
  22. package/dist/src/render/shared/body-formats.d.ts +18 -0
  23. package/dist/src/render/shared/body-formats.js +561 -0
  24. package/dist/src/render/shared/converters.js +57 -4
  25. package/dist/src/render/shared/documentation.d.ts +18 -0
  26. package/dist/src/render/shared/documentation.js +112 -0
  27. package/dist/src/render/shared/openapi.d.ts +1 -1
  28. package/dist/src/render/shared/openapi.js +88 -3
  29. package/dist/src/render/shared/request-selector.d.ts +1 -1
  30. package/dist/src/render/shared/request-selector.js +58 -5
  31. package/dist/src/render/shared/responses.d.ts +55 -0
  32. package/dist/src/render/shared/responses.js +130 -0
  33. package/dist/src/render/shared/routes.js +36 -3
  34. package/package.json +1 -1
  35. package/dist/src/render/minimal/documentation.d.ts +0 -4
  36. package/dist/src/render/minimal/documentation.js +0 -107
@@ -4,6 +4,10 @@ const routeBuilder = `${builder}.EndpointRouteBuilderExtensions`;
4
4
  const groupType = "global::Microsoft.AspNetCore.Routing.RouteGroupBuilder";
5
5
  const withTags = "global::Microsoft.AspNetCore.Http.OpenApiRouteHandlerBuilderExtensions.WithTags";
6
6
  const withMetadata = `${builder}.RoutingEndpointConventionBuilderExtensions.WithMetadata`;
7
+ const withName = `${builder}.RoutingEndpointConventionBuilderExtensions.WithName`;
8
+ const openApi = "global::Microsoft.AspNetCore.Http.OpenApiRouteHandlerBuilderExtensions";
9
+ const withSummary = `${openApi}.WithSummary`;
10
+ const withDescription = `${openApi}.WithDescription`;
7
11
  const mapMethods = {
8
12
  get: "MapGet",
9
13
  put: "MapPut",
@@ -46,6 +50,20 @@ function handler(name, method, { binding, result }) {
46
50
  " }",
47
51
  ].join("\n");
48
52
  }
53
+ /** The calls naming and describing the endpoint held in `endpoint`. */
54
+ function describe(endpoint, found) {
55
+ const { name, summary, description, produces, operation } = found;
56
+ const lines = [` ${withName}(${endpoint}, ${stringLiteral(name)});`];
57
+ if (summary)
58
+ lines.push(` ${withSummary}(${endpoint}, ${stringLiteral(summary)});`);
59
+ if (description) {
60
+ lines.push(` ${withDescription}(${endpoint}, ${stringLiteral(description)});`);
61
+ }
62
+ if (!operation)
63
+ return lines;
64
+ lines.push(` ${withMetadata}(`, ` ${endpoint},`, `${[...produces, operation].map((item) => ` ${item}`).join(",\n")});`);
65
+ return lines;
66
+ }
49
67
  /** The leading segments every route of a group starts with, which the group's builder takes. */
50
68
  function commonPrefix(routes) {
51
69
  let length = 0;
@@ -97,13 +115,17 @@ export function renderEndpoints(rootNamespace, services, routing, handle) {
97
115
  const accepts = found?.accepted.length ? [] : handled[index].binding.accepts;
98
116
  const lines = [
99
117
  ` var endpoint${index} = ${call};`,
100
- ...handled[index].describe(`endpoint${index}`),
118
+ ...describe(`endpoint${index}`, handled[index].documentation),
101
119
  ];
102
120
  if (own)
103
121
  lines.push(` ${withTags}(endpoint${index}, ${list(own)});`);
104
122
  if (accepts.length) {
105
123
  lines.push(` ${withMetadata}(`, ` endpoint${index},`, ` new global::Microsoft.AspNetCore.Http.Metadata.AcceptsMetadata(new string[] { ${list(accepts)} }, ${handled[index].binding.bodyType}));`);
106
124
  }
125
+ const { converted } = handled[index].binding;
126
+ if (converted) {
127
+ lines.push(` global::${rootNamespace}.Requests.BodyFormats.Accept(`, ` endpoint${index},`, ` ${converted.shape},`, ` new string[] { ${list(converted.types)} });`);
128
+ }
107
129
  if (found) {
108
130
  lines.push(` ${withMetadata}(`, ` endpoint${index},`, condition(rootNamespace, found, handled[index].binding.bodyType)
109
131
  .map((line) => ` ${line}`)
@@ -1,5 +1,4 @@
1
- import { reportDiagnostic } from "../../lib.js";
2
- import { isReference } from "../shared/references.js";
1
+ import { arm, responseWriter } from "../shared/responses.js";
3
2
  import { stringLiteral } from "../shared/writer.js";
4
3
  const http = "global::Microsoft.AspNetCore.Http";
5
4
  const results = `${http}.HttpResults`;
@@ -27,8 +26,6 @@ const withoutBody = {
27
26
  409: ["Conflict()", "Conflict"],
28
27
  422: ["UnprocessableEntity()", "UnprocessableEntity"],
29
28
  };
30
- const isText = (type) => type.toLowerCase().startsWith("text/");
31
- const isJson = (type) => /^application\/(?:[\w.-]+\+)?json$/i.test(type.split(";")[0]);
32
29
  /** At most six types fit a `Results<>`, so more are nested in its last place (ADR 0023). */
33
30
  function union(types) {
34
31
  if (types.length === 1)
@@ -48,95 +45,43 @@ function nested(expression, types, index) {
48
45
  }
49
46
  export function resultWriter(program, model, rootNamespace, headers) {
50
47
  const responses = `global::${rootNamespace}.Responses`;
51
- /** The result of one case: its type and the expression making it. */
52
- function respond(found, value, context, operation) {
53
- const { response, content } = found.found;
54
- const member = (name) => found.members.find((m) => m.name === name);
55
- const fixed = typeof response.status === "number" ? response.status : undefined;
56
- const status = fixed === undefined ? `${value}.StatusCode` : String(fixed);
57
- const body = content.body && member("Body");
58
- let type;
59
- let expression;
60
- if (!body) {
48
+ const maker = {
49
+ empty({ fixed, code }) {
61
50
  const known = fixed === undefined ? undefined : withoutBody[fixed];
62
- type = `${results}.${known ? known[1] : "StatusCodeHttpResult"}`;
63
- expression = known ? `${typed}.${known[0]}` : `${typed}.StatusCode(${status})`;
64
- }
65
- else {
66
- const sent = content.body.contentTypes;
67
- const contentType = sent.find((t) => !t.includes("*"));
68
- const sentBody = content.body;
69
- // A nullable value type is a type of its own, which the result must name.
70
- const held = sentBody.kind === "single" && isReference(model, sentBody.type)
71
- ? body.type.replace(/\?$/, "")
72
- : body.type;
73
- const bare = body.type.replace(/\?$/, "");
74
- const read = `${value}.Body`;
75
- if (sent.every(isJson)) {
76
- const own = fixed === undefined ? undefined : withBody[fixed];
77
- if (own && contentType?.toLowerCase() === "application/json") {
78
- type = `${results}.${own}<${held}>`;
79
- const uri = own === "Created" || own === "Accepted" ? "(string?)null, " : "";
80
- expression = `${typed}.${own}<${held}>(${uri}${read})`;
81
- }
82
- else {
83
- type = `${results}.JsonHttpResult<${held}>`;
84
- expression = `${typed}.Json<${held}>(${read}, contentType: ${stringLiteral(contentType ?? "application/json")}, statusCode: ${status})`;
85
- }
51
+ return {
52
+ type: `${results}.${known ? known[1] : "StatusCodeHttpResult"}`,
53
+ expression: known ? `${typed}.${known[0]}` : `${typed}.StatusCode(${code})`,
54
+ };
55
+ },
56
+ json({ fixed, code }, held, body, contentType) {
57
+ const own = fixed === undefined ? undefined : withBody[fixed];
58
+ if (own && contentType?.toLowerCase() === "application/json") {
59
+ const uri = own === "Created" || own === "Accepted" ? "(string?)null, " : "";
60
+ return {
61
+ type: `${results}.${own}<${held}>`,
62
+ expression: `${typed}.${own}<${held}>(${uri}${body})`,
63
+ };
86
64
  }
87
- else if (!sent.some(isJson) &&
88
- (bare === "string" || (bare !== "byte[]" && sent.every(isText)))) {
89
- // Numbers, dates and the like are written as plain text too.
90
- const text = bare === "string" || sentBody.kind !== "single"
91
- ? read
92
- : headers({
93
- type: sentBody.type,
94
- wireName: "body",
95
- source: operation.operation.operation.source,
96
- }, read, body.type);
97
- if (text === undefined)
98
- return undefined;
99
- type = `${results}.ContentHttpResult`;
100
- const named = stringLiteral(contentType ?? "text/plain");
101
- expression = `${typed}.Text(${text}, ${named}, global::System.Text.Encoding.UTF8, ${status})`;
102
- }
103
- else if (bare === "byte[]" && !sent.some(isJson)) {
104
- type = `${responses}.BytesHttpResult`;
105
- const named = stringLiteral(contentType ?? "application/octet-stream");
106
- expression = `new ${type}(${status}, ${read}, ${named})`;
107
- }
108
- else {
109
- reportDiagnostic(program, {
110
- code: "unsupported-type",
111
- format: { kind: `response body sent as ${sent.join(", ")}` },
112
- target: operation.operation.operation.source,
113
- });
114
- return undefined;
115
- }
116
- }
117
- content.headers.forEach((header, index) => {
118
- const name = found.found.headers[index];
119
- const text = headers(header, `${value}.${name}`, member(name).type);
120
- if (text === undefined)
121
- return;
122
- expression = `${responses}.ResponseHeaders.With(${expression}, ${context}, ${stringLiteral(header.wireName)}, ${text})`;
123
- });
124
- return { type, expression };
125
- }
65
+ return {
66
+ type: `${results}.JsonHttpResult<${held}>`,
67
+ expression: `${typed}.Json<${held}>(${body}, contentType: ${stringLiteral(contentType ?? "application/json")}, statusCode: ${code})`,
68
+ };
69
+ },
70
+ text: ({ code }, text, contentType) => ({
71
+ type: `${results}.ContentHttpResult`,
72
+ expression: `${typed}.Text(${text}, ${stringLiteral(contentType)}, global::System.Text.Encoding.UTF8, ${code})`,
73
+ }),
74
+ bytes({ code }, body, contentType) {
75
+ const type = `${responses}.BytesHttpResult`;
76
+ return { type, expression: `new ${type}(${code}, ${body}, ${stringLiteral(contentType)})` };
77
+ },
78
+ };
79
+ const respond = responseWriter(program, model, rootNamespace, headers, maker);
126
80
  /** Maps every case of an operation. `value` and `context` are free names in the handler. */
127
81
  return function map(operation, value, context, namespace) {
128
- const found = operation.cases.flatMap((chosen) => {
129
- const made = respond(chosen, value, context, operation);
130
- return made ? [{ chosen, ...made }] : [];
131
- });
82
+ const found = respond(operation, value, context);
132
83
  const types = [...new Set(found.map((item) => item.type))];
133
- const { name } = operation.operation.result;
134
- const arms = found.map(({ chosen, type, expression }) => {
135
- const held = `global::${namespace}.${name}.${chosen.found.name}`;
136
- const made = nested(expression, types, types.indexOf(type));
137
- const used = made.includes(`${value}.`);
138
- return `${held}${used ? ` ${value}` : ""} => ${made}`;
139
- });
84
+ const arms = found.map(({ chosen, type, expression }) => arm(namespace, operation, chosen, value, nested(expression, types, types.indexOf(type))));
140
85
  return {
141
86
  type: types.length ? union(types) : `${results}.NoContent`,
142
87
  arms,
@@ -6,6 +6,9 @@ import { type Registration } from "./stubs.js";
6
6
  export declare function renderApiSetup(rootNamespace: string, api: string, required: Registration[], endpoints?: {
7
7
  calls: string[];
8
8
  selector: boolean;
9
- validate?: boolean;
9
+ /** True when the generated controllers are to be mapped. */
10
+ controllers?: boolean;
11
+ /** True when handlers or actions check values themselves. */
12
+ checks?: boolean;
10
13
  openapi?: boolean;
11
14
  }): string;
@@ -23,7 +23,14 @@ export function renderApiSetup(rootNamespace, api, required, endpoints = {
23
23
  // A request that cannot be bound then reaches the middleware, which answers it as a problem.
24
24
  register.push(" global::Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure<global::Microsoft.AspNetCore.Routing.RouteHandlerOptions>(\n services, options => options.ThrowOnBadRequest = true);");
25
25
  }
26
- if (endpoints.validate) {
26
+ if (endpoints.controllers) {
27
+ register.push(` global::Microsoft.Extensions.DependencyInjection.MvcCoreMvcBuilderExtensions.AddApplicationPart(
28
+ global::Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllers(services),
29
+ typeof(${api}ApiExtensions).Assembly);`);
30
+ }
31
+ // MVC adds no check of its own: the generated controllers check as Minimal APIs do.
32
+ const validation = (minimal || endpoints.controllers) && endpoints.checks;
33
+ if (validation) {
27
34
  // Called here, in the assembly whose endpoints take the types to be checked.
28
35
  // As deep as JSON is read, so that a deep body is judged rather than a fault.
29
36
  register.push(" services.AddValidation(options => options.MaxDepth = 64);");
@@ -38,31 +45,57 @@ export function renderApiSetup(rootNamespace, api, required, endpoints = {
38
45
  global::Microsoft.AspNetCore.Routing.MatcherPolicy,
39
46
  global::${rootNamespace}.Routing.RequestSelector>());`);
40
47
  }
48
+ const document = endpoints.openapi
49
+ ? [
50
+ " // The document describes the API, so only development serves it.",
51
+ " if (global::Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))",
52
+ " {",
53
+ " global::Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.MapOpenApi(app);",
54
+ " }",
55
+ "",
56
+ ]
57
+ : [];
58
+ const controllers = endpoints.controllers
59
+ ? [
60
+ " global::Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllers(app);",
61
+ ...document,
62
+ ].join("\n") + "\n"
63
+ : "";
64
+ const write = (result) => endpoints.controllers
65
+ ? `await WriteProblem(context, ${result});`
66
+ : `await ${result}.ExecuteAsync(context);`;
67
+ const writeProblem = endpoints.controllers
68
+ ? `
69
+ // MVC writes the problems of its actions its own way, leaving out the errors of a value, so
70
+ // the action is set aside while a problem is written as for a Minimal API endpoint.
71
+ private static async global::System.Threading.Tasks.Task WriteProblem(
72
+ global::Microsoft.AspNetCore.Http.HttpContext context,
73
+ global::Microsoft.AspNetCore.Http.IResult problem)
74
+ {
75
+ var endpoint = global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.GetEndpoint(context);
76
+ global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.SetEndpoint(context, null);
77
+ try
78
+ {
79
+ await problem.ExecuteAsync(context);
80
+ }
81
+ finally
82
+ {
83
+ global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.SetEndpoint(context, endpoint);
84
+ }
85
+ }
86
+ `
87
+ : "";
41
88
  const mapped = endpoints.calls.length
42
89
  ? [
43
90
  ' var api = global::Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapGroup(app, "");',
44
91
  " global::Microsoft.AspNetCore.Builder.RoutingEndpointConventionBuilderExtensions.WithMetadata(api, new GeneratedEndpoint());",
45
92
  " global::Microsoft.AspNetCore.Http.EndpointFilterExtensions.AddEndpointFilter(api, Bound);",
46
93
  ...endpoints.calls.map((call) => ` ${call}(api);`),
47
- ...(endpoints.openapi
48
- ? [
49
- " // The document describes the API, so only development serves it.",
50
- " if (global::Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))",
51
- " {",
52
- " global::Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.MapOpenApi(app);",
53
- " }",
54
- "",
55
- ]
56
- : []),
94
+ ...document,
57
95
  ].join("\n") + "\n"
58
- : "";
59
- const summary = endpoints.calls.length
60
- ? ` /// <summary>
96
+ : controllers;
97
+ const summary = ` /// <summary>
61
98
  /// Maps the routes of the API, after checking that every service is registered.
62
- /// </summary>`
63
- : ` /// <summary>
64
- /// Maps the routes of the API, after checking that every service is registered. No routes are
65
- /// generated for this style yet.
66
99
  /// </summary>`;
67
100
  const isService = "global::Microsoft.Extensions.DependencyInjection.IServiceProviderIsService";
68
101
  const application = "global::Microsoft.AspNetCore.Builder.WebApplication";
@@ -102,7 +135,7 @@ ${required
102
135
  : ` /// <summary>Maps the routes of the API. No routes are generated yet.</summary>
103
136
  public static ${application} Map${api}Api(
104
137
  this ${application} app) => app;`;
105
- const usings = endpoints.validate ? ["global::Microsoft.Extensions.DependencyInjection"] : [];
138
+ const usings = validation ? ["global::Microsoft.Extensions.DependencyInjection"] : [];
106
139
  return csharpFile(rootNamespace, `/// <summary>Sets up the generated API in a host.</summary>
107
140
  public static class ${api}ApiExtensions
108
141
  {
@@ -178,7 +211,7 @@ ${minimal
178
211
  global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
179
212
  await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: 501).ExecuteAsync(context);
180
213
  }
181
- ${endpoints.validate
214
+ ${endpoints.checks
182
215
  ? ` catch (global::${rootNamespace}.Requests.RequestInvalidException exception)
183
216
  when (!context.Response.HasStarted)
184
217
  {
@@ -187,7 +220,7 @@ ${endpoints.validate
187
220
  {
188
221
  [exception.Name] = new string[] { exception.Message },
189
222
  };
190
- await global::Microsoft.AspNetCore.Http.Results.ValidationProblem(errors).ExecuteAsync(context);
223
+ ${write("global::Microsoft.AspNetCore.Http.Results.ValidationProblem(errors)")}
191
224
  }
192
225
  `
193
226
  : ""}${minimal
@@ -214,9 +247,10 @@ ${endpoints.validate
214
247
  global::Microsoft.Extensions.Logging.LoggerExtensions.LogDebug(
215
248
  logs.CreateLogger("${rootNamespace}"), exception, "The request cannot be read.");
216
249
  global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
217
- await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: exception.StatusCode)
218
- .ExecuteAsync(context);
250
+ ${endpoints.controllers
251
+ ? write("global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: exception.StatusCode)")
252
+ : "await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: exception.StatusCode)\n .ExecuteAsync(context);"}
219
253
  }
220
254
  }
221
- }`, usings);
255
+ ${writeProblem}}`, usings);
222
256
  }
@@ -1,6 +1,7 @@
1
1
  import type { Program } from "@typespec/compiler";
2
2
  import type { ApiModel } from "../../model/types.js";
3
3
  import type { OperationName } from "../../naming/services.js";
4
+ import { type BodyShapes } from "./body-formats.js";
4
5
  import type { TypeText } from "./services.js";
5
6
  export type Source = "route" | "query" | "header" | "body" | "service" | "context" | "cancellation";
6
7
  /** A parameter of a handler. */
@@ -19,15 +20,24 @@ export interface Binding {
19
20
  values: string[];
20
21
  /** Content types of a body that is read by hand, which the endpoint must declare. */
21
22
  accepts: string[];
23
+ /** Set when form or XML bodies are turned into JSON: the shape and content types. */
24
+ converted?: {
25
+ shape: string;
26
+ types: string[];
27
+ };
22
28
  /** `typeof` the body, which a declared content type is said to hold. */
23
29
  bodyType?: string;
24
30
  /** The expressions making the constraints of each parameter, by its position. */
25
31
  checks: Map<number, string[]>;
32
+ /** How the handler reaches the request's context. */
33
+ context: string;
26
34
  /** Names the handler can use for the service's result and a case of it. */
27
35
  result: string;
28
36
  found: string;
29
37
  }
30
- export declare function bindingWriter(program: Program, model: ApiModel, rootNamespace: string, typeOf: TypeText): (named: OperationName, service: string, signature: {
38
+ export declare function bindingWriter(program: Program, model: ApiModel, rootNamespace: string, typeOf: TypeText, shapes: BodyShapes,
39
+ /** A controller holds its service and context, so its actions declare neither. */
40
+ controllers?: boolean): (named: OperationName, service: string, signature: {
31
41
  type: string;
32
42
  name: string;
33
43
  }[], writes: boolean) => Binding;
@@ -1,4 +1,5 @@
1
1
  import { reportDiagnostic } from "../../lib.js";
2
+ import { isForm, isXml } from "./body-formats.js";
2
3
  import { isReference } from "./references.js";
3
4
  import { mapScalar, numberLiteral, systemTypes } from "./scalars.js";
4
5
  import { holds, uncheckedConstraints, unreached, validationAttributes } from "./validation.js";
@@ -7,7 +8,9 @@ const nativeTypes = new Set("string bool sbyte short int long byte ushort uint u
7
8
  const nullable = (type) => (type.endsWith("?") ? type : `${type}?`);
8
9
  const bare = (ref) => (ref.kind === "nullable" ? bare(ref.type) : ref);
9
10
  const isJson = (type) => /^application\/(?:[\w.-]+\+)?json$/i.test(type.split(";")[0]);
10
- export function bindingWriter(program, model, rootNamespace, typeOf) {
11
+ export function bindingWriter(program, model, rootNamespace, typeOf, shapes,
12
+ /** A controller holds its service and context, so its actions declare neither. */
13
+ controllers = false) {
11
14
  const parameters = `global::${rootNamespace}.Requests.Parameters`;
12
15
  function refuse(what, target) {
13
16
  reportDiagnostic(program, { code: "unsupported-type", format: { kind: what }, target });
@@ -172,7 +175,9 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
172
175
  : convert(split(name));
173
176
  return { parameter, value };
174
177
  }
175
- function bindParameter(input, name, context) {
178
+ function bindParameter(input, name, context,
179
+ /** Where the text is read from, when the handler does not declare it. */
180
+ held) {
176
181
  const type = bare(input.type);
177
182
  // Such as pipe delimited arrays, which are not read yet.
178
183
  if (type.kind === "array") {
@@ -186,9 +191,12 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
186
191
  return undefined;
187
192
  const optional = input.optional || input.default !== undefined;
188
193
  const given = input.default;
189
- if (input.in !== "cookie" && found.native) {
194
+ // A cookie is never declared on the handler, so its location is never one.
195
+ const location = input.in === "path" ? "route" : input.in;
196
+ const stored = input.in === "cookie" ? `${context}.Request.Cookies[${stringLiteral(input.wireName)}]` : held;
197
+ if (!stored && found.native) {
190
198
  const parameter = {
191
- source: input.in === "path" ? "route" : input.in,
199
+ source: location,
192
200
  wireName: input.wireName,
193
201
  // A required value must be sent, even when the service may be given null.
194
202
  type: optional ? nullable(found.type) : found.type,
@@ -205,17 +213,16 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
205
213
  if (given !== undefined && given !== null && text === undefined)
206
214
  notApplied(input);
207
215
  const missing = text === undefined ? undefined : stringLiteral(text);
208
- if (input.in === "cookie") {
209
- const cookie = `${context}.Request.Cookies[${stringLiteral(input.wireName)}]`;
216
+ if (stored) {
210
217
  const value = missing
211
- ? found.read(`${cookie} ?? ${missing}`)
218
+ ? found.read(`${stored} ?? ${missing}`)
212
219
  : optional
213
- ? `${cookie} is { } ${name} ? ${found.read(name)} : null`
214
- : found.read(`${parameters}.Required(${cookie}, ${stringLiteral(input.wireName)})`);
220
+ ? `${stored} is { } ${name} ? ${found.read(name)} : null`
221
+ : found.read(`${parameters}.Required(${stored}, ${stringLiteral(input.wireName)})`);
215
222
  return { value };
216
223
  }
217
224
  const parameter = {
218
- source: input.in === "path" ? "route" : input.in,
225
+ source: location,
219
226
  wireName: input.wireName,
220
227
  type: optional ? "string?" : "string",
221
228
  name,
@@ -283,20 +290,28 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
283
290
  taken.add(name);
284
291
  return name;
285
292
  };
286
- const serviceName = free("service");
287
- const context = free("httpContext");
293
+ const serviceName = controllers ? "" : free("service");
294
+ const context = controllers ? "this.HttpContext" : free("httpContext");
288
295
  const found = {
289
296
  parameters: [],
290
297
  values: [],
291
298
  accepts: [],
292
299
  checks: new Map(),
300
+ context,
293
301
  result: free("result"),
294
302
  found: free("found"),
295
303
  };
296
304
  // The response may need the context too.
297
305
  let usesContext = writes;
306
+ // Whether form or XML bodies are turned into JSON, which changes the content type.
307
+ const converts = operation.body?.kind === "single" &&
308
+ operation.body.contentTypes.some((t) => isForm(t) || isXml(t));
298
309
  operation.parameters.forEach((input, index) => {
299
- const read = bindParameter(input, named.parameters[index], context);
310
+ const held = converts && input.in === "header" && input.wireName.toLowerCase() === "content-type"
311
+ ? `global::${rootNamespace}.Requests.BodyFormats.SentType(${context}.Request)`
312
+ : undefined;
313
+ // So a content type is kept from the request as it came.
314
+ const read = bindParameter(input, named.parameters[index], context, held);
300
315
  if (!read)
301
316
  return;
302
317
  const bound = constrain(input, read, {
@@ -332,7 +347,26 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
332
347
  target: operation.source,
333
348
  });
334
349
  }
335
- if (body.kind === "single" && body.contentTypes.every(isJson)) {
350
+ const types = body.contentTypes;
351
+ const held = type.replace(/\?$/, "");
352
+ // Form and XML bodies of anything but plain text and bytes are turned into JSON.
353
+ const convert = body.kind === "single" &&
354
+ types.every((t) => isJson(t) || isForm(t) || isXml(t)) &&
355
+ !types.every(isJson) &&
356
+ (types.some((t) => isJson(t) || isForm(t)) || (held !== "string" && held !== "byte[]"));
357
+ if (body.kind === "single" && (convert || types.every(isJson))) {
358
+ if (convert) {
359
+ const merge = types.some((t) => t.includes("merge-patch"));
360
+ const read = merge
361
+ ? { problem: "merge patch sent as form or XML too" }
362
+ : shapes.of(body.type, types);
363
+ if ("problem" in read)
364
+ refuse(read.problem, operation.source);
365
+ else {
366
+ found.converted = { shape: read.shape, types: types.filter((t) => !isJson(t)) };
367
+ found.accepts = types;
368
+ }
369
+ }
336
370
  found.parameters.push({
337
371
  source: "body",
338
372
  type,
@@ -343,7 +377,6 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
343
377
  }
344
378
  else {
345
379
  // ASP.NET Core reads only JSON, so text and bytes are read by hand.
346
- const held = type.replace(/\?$/, "");
347
380
  const text = body.contentTypes.every((t) => t.toLowerCase().startsWith("text/"));
348
381
  const method = held === "byte[]" ? "Bytes" : text || held === "string" ? "Text" : undefined;
349
382
  if (body.kind !== "single" || !method || body.contentTypes.some(isJson)) {
@@ -372,12 +405,10 @@ export function bindingWriter(program, model, rootNamespace, typeOf) {
372
405
  }
373
406
  }
374
407
  }
375
- found.parameters.push({
376
- source: "service",
377
- type: service,
378
- name: serviceName,
379
- });
380
- if (usesContext) {
408
+ if (!controllers) {
409
+ found.parameters.push({ source: "service", type: service, name: serviceName });
410
+ }
411
+ if (usesContext && !controllers) {
381
412
  found.parameters.push({
382
413
  source: "context",
383
414
  type: "global::Microsoft.AspNetCore.Http.HttpContext",
@@ -0,0 +1,18 @@
1
+ import { type Program } from "@typespec/compiler";
2
+ import type { ApiModel, TypeRef } from "../../model/types.js";
3
+ export declare const isForm: (type: string) => boolean;
4
+ export declare const isXml: (type: string) => boolean;
5
+ export declare function bodyShapes(program: Program, model: ApiModel, rootNamespace: string): {
6
+ /**
7
+ * The expression naming the shape of a body, or what keeps it from being read as one of the
8
+ * content types.
9
+ */
10
+ of(ref: TypeRef, contentTypes: string[]): {
11
+ shape: string;
12
+ } | {
13
+ problem: string;
14
+ };
15
+ /** The generated file, when any body uses it. */
16
+ render(controllers?: boolean): string | undefined;
17
+ };
18
+ export type BodyShapes = ReturnType<typeof bodyShapes>;