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.
Files changed (49) hide show
  1. package/README.md +11 -4
  2. package/dist/src/emitter.js +104 -5
  3. package/dist/src/lib.d.ts +47 -2
  4. package/dist/src/lib.js +18 -0
  5. package/dist/src/model/collect-types.d.ts +3 -1
  6. package/dist/src/model/collect-types.js +1 -1
  7. package/dist/src/model/collect.js +56 -6
  8. package/dist/src/model/types.d.ts +12 -0
  9. package/dist/src/naming/names.d.ts +1 -1
  10. package/dist/src/naming/names.js +13 -3
  11. package/dist/src/naming/services.d.ts +11 -1
  12. package/dist/src/naming/services.js +18 -3
  13. package/dist/src/render/controllers/controllers.d.ts +20 -0
  14. package/dist/src/render/controllers/controllers.js +559 -0
  15. package/dist/src/render/controllers/results.d.ts +10 -0
  16. package/dist/src/render/controllers/results.js +82 -0
  17. package/dist/src/render/minimal/endpoints.d.ts +14 -0
  18. package/dist/src/render/minimal/endpoints.js +161 -0
  19. package/dist/src/render/minimal/results.d.ts +11 -0
  20. package/dist/src/render/minimal/results.js +90 -0
  21. package/dist/src/render/shared/api-setup.d.ts +9 -1
  22. package/dist/src/render/shared/api-setup.js +165 -11
  23. package/dist/src/render/shared/binding.d.ts +43 -0
  24. package/dist/src/render/shared/binding.js +426 -0
  25. package/dist/src/render/shared/body-formats.d.ts +18 -0
  26. package/dist/src/render/shared/body-formats.js +561 -0
  27. package/dist/src/render/shared/converters.js +57 -4
  28. package/dist/src/render/shared/documentation.d.ts +18 -0
  29. package/dist/src/render/shared/documentation.js +112 -0
  30. package/dist/src/render/shared/headers.d.ts +7 -0
  31. package/dist/src/render/shared/headers.js +52 -0
  32. package/dist/src/render/shared/models.js +5 -23
  33. package/dist/src/render/shared/openapi.d.ts +1 -0
  34. package/dist/src/render/shared/openapi.js +333 -0
  35. package/dist/src/render/shared/parameters.d.ts +3 -0
  36. package/dist/src/render/shared/parameters.js +224 -0
  37. package/dist/src/render/shared/references.d.ts +3 -0
  38. package/dist/src/render/shared/references.js +18 -0
  39. package/dist/src/render/shared/request-selector.d.ts +1 -0
  40. package/dist/src/render/shared/request-selector.js +139 -0
  41. package/dist/src/render/shared/responses.d.ts +55 -0
  42. package/dist/src/render/shared/responses.js +130 -0
  43. package/dist/src/render/shared/routes.d.ts +37 -0
  44. package/dist/src/render/shared/routes.js +274 -0
  45. package/dist/src/render/shared/validation.d.ts +6 -1
  46. package/dist/src/render/shared/validation.js +60 -0
  47. package/dist/src/scaffold/projects.d.ts +1 -1
  48. package/dist/src/scaffold/projects.js +4 -3
  49. package/package.json +2 -2
@@ -0,0 +1,426 @@
1
+ import { reportDiagnostic } from "../../lib.js";
2
+ import { isForm, isXml } from "./body-formats.js";
3
+ import { isReference } from "./references.js";
4
+ import { mapScalar, numberLiteral, systemTypes } from "./scalars.js";
5
+ import { holds, uncheckedConstraints, unreached, validationAttributes } from "./validation.js";
6
+ import { stringLiteral } from "./writer.js";
7
+ const nativeTypes = new Set("string bool sbyte short int long byte ushort uint ulong float double decimal".split(" "));
8
+ const nullable = (type) => (type.endsWith("?") ? type : `${type}?`);
9
+ const bare = (ref) => (ref.kind === "nullable" ? bare(ref.type) : ref);
10
+ const isJson = (type) => /^application\/(?:[\w.-]+\+)?json$/i.test(type.split(";")[0]);
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) {
14
+ const parameters = `global::${rootNamespace}.Requests.Parameters`;
15
+ function refuse(what, target) {
16
+ reportDiagnostic(program, { code: "unsupported-type", format: { kind: what }, target });
17
+ return undefined;
18
+ }
19
+ /** A reader that parses text as the JSON of the type would be read. */
20
+ function parsed(type, name, number, converter) {
21
+ const generic = converter ? `${type}, ${converter}` : type;
22
+ return {
23
+ type,
24
+ native: false,
25
+ read: (text) => `${parameters}.Value<${generic}>(${text}, ${number}, ${stringLiteral(name)})`,
26
+ };
27
+ }
28
+ function scalarReader(builtin, encoding, wireName, target) {
29
+ const mapped = mapScalar(builtin, encoding);
30
+ if (!mapped)
31
+ return refuse(`${builtin} with this encoding`, target);
32
+ const type = systemTypes.has(mapped.type) ? `global::System.${mapped.type}` : mapped.type;
33
+ if (type === "string")
34
+ return { type, native: true, read: (text) => text };
35
+ if (nativeTypes.has(type))
36
+ return { ...parsed(type, wireName, true), native: true };
37
+ const converter = mapped.attributes
38
+ .map((attribute) => /^JsonConverter\(typeof\((\w+)\)\)$/.exec(attribute)?.[1])
39
+ .find(Boolean);
40
+ const number = encoding !== undefined && encoding.wireType !== "string";
41
+ return parsed(type, wireName, number, converter && `global::${rootNamespace}.Serialization.${converter}`);
42
+ }
43
+ function reader(ref, encoding, wireName, target) {
44
+ const value = bare(ref);
45
+ if (value.kind === "scalar")
46
+ return scalarReader(value.name, encoding, wireName, target);
47
+ if (value.kind === "literal") {
48
+ const type = typeOf(value, target);
49
+ return type === "string"
50
+ ? { type, native: true, read: (text) => text }
51
+ : { ...parsed(type, wireName, true), native: true };
52
+ }
53
+ if (value.kind !== "named" && value.kind !== "enumMember") {
54
+ return refuse(`${value.kind} in a ${wireName} parameter`, target);
55
+ }
56
+ const declared = model.types.get(value.kind === "named" ? value.id : value.enum);
57
+ if (declared.kind === "scalar") {
58
+ return declared.builtin
59
+ ? scalarReader(declared.builtin, encoding, wireName, target)
60
+ : refuse(`scalar "${declared.name}" that derives from no built-in`, target);
61
+ }
62
+ const type = typeOf(value, target);
63
+ if (declared.kind === "enum") {
64
+ return parsed(type, wireName, typeof declared.members[0]?.value === "number");
65
+ }
66
+ // A union of strings is read from its text; other unions have no one way to be written.
67
+ const strings = declared.kind === "union" &&
68
+ declared.variants.every(({ type: variant }) => variant.kind === "literal"
69
+ ? typeof variant.value === "string"
70
+ : variant.kind === "scalar" && variant.name === "string");
71
+ return strings
72
+ ? parsed(type, wireName, false)
73
+ : refuse(`${declared.kind} in a parameter`, target);
74
+ }
75
+ /** The default of a native value, as a C# literal. */
76
+ function literal(value, type) {
77
+ if (type === "string")
78
+ return typeof value === "string" ? stringLiteral(value) : undefined;
79
+ if (type === "bool")
80
+ return typeof value === "boolean" ? String(value) : undefined;
81
+ const builtin = {
82
+ sbyte: "int8",
83
+ short: "int16",
84
+ int: "int32",
85
+ long: "int64",
86
+ byte: "uint8",
87
+ ushort: "uint16",
88
+ uint: "uint32",
89
+ ulong: "uint64",
90
+ float: "float32",
91
+ double: "float64",
92
+ decimal: "decimal",
93
+ };
94
+ return typeof value === "number" || typeof value === "string"
95
+ ? numberLiteral(String(value), builtin[type])
96
+ : undefined;
97
+ }
98
+ /** The default of a value, as the text a request would hold. */
99
+ function defaultText(value, encoding) {
100
+ if (!["string", "number", "boolean"].includes(typeof value))
101
+ return undefined;
102
+ // The default is given as ISO 8601, whatever the date is encoded as in a header.
103
+ if (encoding?.name === "rfc7231" && !Number.isNaN(Date.parse(String(value)))) {
104
+ return new Date(String(value)).toUTCString();
105
+ }
106
+ return String(value);
107
+ }
108
+ function notApplied(input) {
109
+ reportDiagnostic(program, {
110
+ code: "unsupported-type",
111
+ format: { kind: `default value of the parameter "${input.name}"` },
112
+ target: input.source,
113
+ });
114
+ }
115
+ function bindList(input, element, name, context) {
116
+ const item = reader(element, input.encoding, input.wireName, input.source);
117
+ if (!item)
118
+ return undefined;
119
+ const itemType = element.kind === "nullable" ? nullable(item.type) : item.type;
120
+ const convert = (list) => item.type === "string"
121
+ ? list
122
+ : `${parameters}.List<${itemType}>(${list}, item => ${item.read("item")})`;
123
+ // The wire text of each item of the default.
124
+ const items = Array.isArray(input.default)
125
+ ? input.default.map((value) => defaultText(value, input.encoding))
126
+ : undefined;
127
+ if (input.default !== undefined && (!items || items.includes(undefined)))
128
+ notApplied(input);
129
+ const fallback = items && `new string[] { ${items.map((text) => stringLiteral(text ?? "")).join(", ")} }`;
130
+ const optional = input.optional && input.default === undefined;
131
+ // A repeated query value is a list already.
132
+ if (input.in === "query" && input.explode) {
133
+ const bound = item.native ? itemType : "string";
134
+ const parameter = {
135
+ source: "query",
136
+ wireName: input.wireName,
137
+ type: `${bound}[]`,
138
+ name,
139
+ };
140
+ const list = item.native ? name : convert(name);
141
+ const other = fallback && (item.native ? convert(fallback) : convert(fallback));
142
+ // An empty list cannot be written, so none sent is none given.
143
+ const value = other
144
+ ? `${name}.Length == 0 ? ${other} : ${list}`
145
+ : optional
146
+ ? `${name}.Length == 0 ? null : ${list}`
147
+ : list;
148
+ return { parameter, value };
149
+ }
150
+ const headers = input.in === "header";
151
+ // An HTTP date holds a comma of its own.
152
+ const split = (text) => input.encoding?.name === "rfc7231"
153
+ ? `${parameters}.SplitDates(${text})`
154
+ : `${parameters}.Split(${text}, ${headers})`;
155
+ if (input.in === "cookie") {
156
+ const text = `${context}.Request.Cookies[${stringLiteral(input.wireName)}]`;
157
+ const sent = `${parameters}.Required(${text}, ${stringLiteral(input.wireName)})`;
158
+ const value = fallback
159
+ ? `${text} is { } ${name} ? ${convert(split(name))} : ${convert(fallback)}`
160
+ : optional
161
+ ? `${text} is { } ${name} ? ${convert(split(name))} : null`
162
+ : convert(split(sent));
163
+ return { value };
164
+ }
165
+ const parameter = {
166
+ source: input.in === "path" ? "route" : input.in,
167
+ wireName: input.wireName,
168
+ type: input.optional || input.default !== undefined ? "string?" : "string",
169
+ name,
170
+ };
171
+ const value = fallback
172
+ ? `${name} is null ? ${convert(fallback)} : ${convert(split(name))}`
173
+ : optional
174
+ ? `${name} is null ? null : ${convert(split(name))}`
175
+ : convert(split(name));
176
+ return { parameter, value };
177
+ }
178
+ function bindParameter(input, name, context,
179
+ /** Where the text is read from, when the handler does not declare it. */
180
+ held) {
181
+ const type = bare(input.type);
182
+ // Such as pipe delimited arrays, which are not read yet.
183
+ if (type.kind === "array") {
184
+ if (input.encoding?.name?.startsWith("ArrayEncoding.")) {
185
+ return refuse(`array parameter encoded as ${input.encoding.name}`, input.source);
186
+ }
187
+ return bindList(input, type.element, name, context);
188
+ }
189
+ const found = reader(input.type, input.encoding, input.wireName, input.source);
190
+ if (!found)
191
+ return undefined;
192
+ const optional = input.optional || input.default !== undefined;
193
+ const given = input.default;
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) {
198
+ const parameter = {
199
+ source: location,
200
+ wireName: input.wireName,
201
+ // A required value must be sent, even when the service may be given null.
202
+ type: optional ? nullable(found.type) : found.type,
203
+ name,
204
+ };
205
+ if (given === undefined || given === null)
206
+ return { parameter, value: name };
207
+ const other = literal(given, found.type);
208
+ if (other === undefined)
209
+ notApplied(input);
210
+ return { parameter, value: `${name} ?? ${other}` };
211
+ }
212
+ const text = given === undefined || given === null ? undefined : defaultText(given, input.encoding);
213
+ if (given !== undefined && given !== null && text === undefined)
214
+ notApplied(input);
215
+ const missing = text === undefined ? undefined : stringLiteral(text);
216
+ if (stored) {
217
+ const value = missing
218
+ ? found.read(`${stored} ?? ${missing}`)
219
+ : optional
220
+ ? `${stored} is { } ${name} ? ${found.read(name)} : null`
221
+ : found.read(`${parameters}.Required(${stored}, ${stringLiteral(input.wireName)})`);
222
+ return { value };
223
+ }
224
+ const parameter = {
225
+ source: location,
226
+ wireName: input.wireName,
227
+ type: optional ? "string?" : "string",
228
+ name,
229
+ };
230
+ const value = missing
231
+ ? found.read(`${name} ?? ${missing}`)
232
+ : optional
233
+ ? `${name} is null ? null : ${found.read(name)}`
234
+ : found.read(name);
235
+ return { parameter, value };
236
+ }
237
+ /**
238
+ * Adds the checks of a parameter. ASP.NET Core checks those on a handler's parameter; a list
239
+ * or a cookie is checked once it is read.
240
+ */
241
+ function constrain(input, bound, given) {
242
+ const kind = holds(model, input.type);
243
+ const unchecked = [
244
+ ...uncheckedConstraints(input.constraints ?? {}, kind),
245
+ ...(input.heldConstraints ?? []),
246
+ ];
247
+ for (const name of unchecked) {
248
+ reportDiagnostic(program, {
249
+ code: "constraint-not-checked",
250
+ format: { name },
251
+ target: input.source,
252
+ });
253
+ }
254
+ const attributes = validationAttributes(input.constraints ?? {}, kind, `global::${rootNamespace}.Validation`);
255
+ if (attributes.length === 0)
256
+ return bound;
257
+ if (bound.parameter && kind !== "array") {
258
+ return { ...bound, parameter: { ...bound.parameter, attributes } };
259
+ }
260
+ return { ...bound, value: check(bound.value, given, attributes) };
261
+ }
262
+ /** Checks a value where it is used, naming it as ASP.NET Core names a handler's parameter. */
263
+ function check(value, given, attributes) {
264
+ const name = stringLiteral(given.name.replace(/^@/, ""));
265
+ // The type is written, as a value that may be left out has none of its own.
266
+ const list = attributes.map(construct).join(", ");
267
+ return `${parameters}.Check<${given.type}>(${value}, ${name}, ${list})`;
268
+ }
269
+ /** The expression making an attribute written as `Name(arguments, Property = value)`. */
270
+ function construct(attribute) {
271
+ const open = attribute.indexOf("(");
272
+ const type = `${attribute.slice(0, open)}Attribute`;
273
+ const list = attribute.slice(open + 1, -1);
274
+ // Text in a string is not an argument.
275
+ const outside = list.replace(/"(?:\\.|[^"\\])*"/g, (text) => "_".repeat(text.length));
276
+ const named = outside.search(/(?:^|, )[A-Z]\w* = /);
277
+ if (named < 0)
278
+ return `new ${type}(${list})`;
279
+ const properties = list.slice(named).replace(/^, /, "");
280
+ return `new ${type}(${list.slice(0, named)}) { ${properties} }`;
281
+ }
282
+ /** Reads every input of an operation, naming the handler's own parameters apart from them. */
283
+ return function bind(named, service, signature, writes) {
284
+ const { operation } = named;
285
+ const taken = new Set(signature.map((parameter) => parameter.name));
286
+ const free = (wanted) => {
287
+ let name = wanted;
288
+ for (let number = 2; taken.has(name); number++)
289
+ name = `${wanted}${number}`;
290
+ taken.add(name);
291
+ return name;
292
+ };
293
+ const serviceName = controllers ? "" : free("service");
294
+ const context = controllers ? "this.HttpContext" : free("httpContext");
295
+ const found = {
296
+ parameters: [],
297
+ values: [],
298
+ accepts: [],
299
+ checks: new Map(),
300
+ context,
301
+ result: free("result"),
302
+ found: free("found"),
303
+ };
304
+ // The response may need the context too.
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));
309
+ operation.parameters.forEach((input, index) => {
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);
315
+ if (!read)
316
+ return;
317
+ const bound = constrain(input, read, {
318
+ name: named.parameters[index],
319
+ type: signature[index].type,
320
+ });
321
+ if (bound.parameter)
322
+ found.parameters.push(bound.parameter);
323
+ else
324
+ usesContext = true;
325
+ const checks = validationAttributes(input.constraints ?? {}, holds(model, input.type), `global::${rootNamespace}.Validation`);
326
+ if (checks.length)
327
+ found.checks.set(index, checks.map(construct));
328
+ found.values.push(bound.value);
329
+ });
330
+ const { body } = operation;
331
+ if (body) {
332
+ const name = named.body;
333
+ const type = signature[operation.parameters.length].type;
334
+ const reference = body.kind !== "single" || isReference(model, body.type);
335
+ found.bodyType = `typeof(${reference ? type.replace(/\?$/, "") : type})`;
336
+ const kind = body.kind === "single" ? holds(model, body.type) : "other";
337
+ const attributes = validationAttributes(body.constraints ?? {}, kind, `global::${rootNamespace}.Validation`);
338
+ const unchecked = [
339
+ ...uncheckedConstraints(body.constraints ?? {}, kind),
340
+ ...(body.heldConstraints ?? []),
341
+ ...(body.kind === "single" ? [unreached(model, body.type) ?? []].flat() : []),
342
+ ];
343
+ for (const constraint of unchecked) {
344
+ reportDiagnostic(program, {
345
+ code: "constraint-not-checked",
346
+ format: { name: constraint },
347
+ target: operation.source,
348
+ });
349
+ }
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
+ }
370
+ found.parameters.push({
371
+ source: "body",
372
+ type,
373
+ name,
374
+ ...(attributes.length && { attributes }),
375
+ });
376
+ found.values.push(name);
377
+ }
378
+ else {
379
+ // ASP.NET Core reads only JSON, so text and bytes are read by hand.
380
+ const text = body.contentTypes.every((t) => t.toLowerCase().startsWith("text/"));
381
+ const method = held === "byte[]" ? "Bytes" : text || held === "string" ? "Text" : undefined;
382
+ if (body.kind !== "single" || !method || body.contentTypes.some(isJson)) {
383
+ refuse(`body sent as ${body.contentTypes.join(", ")}`, operation.source);
384
+ }
385
+ else {
386
+ usesContext = true;
387
+ const cancellation = named.cancellation;
388
+ const sent = `await ${parameters}.${method}(${context}.Request, ${body.optional}, ${cancellation})`;
389
+ const checked = (value) => attributes.length ? check(value, { name, type }, attributes) : value;
390
+ if (method === "Bytes" || held === "string") {
391
+ found.values.push(checked(sent));
392
+ }
393
+ else {
394
+ // Other values sent as text are read as parameters are.
395
+ const parsed = reader(body.type, undefined, name, operation.source);
396
+ if (parsed) {
397
+ const text = free("text");
398
+ const read = parsed.read(text);
399
+ found.values.push(checked(body.optional
400
+ ? `${sent} is { } ${text} ? ${read} : null`
401
+ : `${parameters}.With(${sent}, ${text} => ${read})`));
402
+ }
403
+ }
404
+ found.accepts = body.contentTypes.filter((type) => !type.includes("*"));
405
+ }
406
+ }
407
+ }
408
+ if (!controllers) {
409
+ found.parameters.push({ source: "service", type: service, name: serviceName });
410
+ }
411
+ if (usesContext && !controllers) {
412
+ found.parameters.push({
413
+ source: "context",
414
+ type: "global::Microsoft.AspNetCore.Http.HttpContext",
415
+ name: context,
416
+ });
417
+ }
418
+ found.parameters.push({
419
+ source: "cancellation",
420
+ type: "global::System.Threading.CancellationToken",
421
+ name: named.cancellation,
422
+ });
423
+ found.values.push(named.cancellation);
424
+ return found;
425
+ };
426
+ }
@@ -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>;