typespec-rust-emitter 0.11.0 → 0.13.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 (141) hide show
  1. package/AGENTS.md +83 -79
  2. package/CHANGELOG.md +60 -0
  3. package/dist/src/decorators/cache_control.d.ts +6 -0
  4. package/dist/src/decorators/cache_control.js +9 -0
  5. package/dist/src/decorators/cache_control.js.map +1 -0
  6. package/dist/src/decorators/etag_cache.d.ts +6 -0
  7. package/dist/src/decorators/etag_cache.js +9 -0
  8. package/dist/src/decorators/etag_cache.js.map +1 -0
  9. package/dist/src/decorators/index.d.ts +6 -0
  10. package/dist/src/decorators/index.js +7 -0
  11. package/dist/src/decorators/index.js.map +1 -0
  12. package/dist/src/decorators/rust_attr.d.ts +3 -0
  13. package/dist/src/decorators/rust_attr.js +45 -0
  14. package/dist/src/decorators/rust_attr.js.map +1 -0
  15. package/dist/src/decorators/rust_derive.d.ts +3 -0
  16. package/dist/src/decorators/rust_derive.js +39 -0
  17. package/dist/src/decorators/rust_derive.js.map +1 -0
  18. package/dist/src/decorators/rust_impl.d.ts +2 -0
  19. package/dist/src/decorators/rust_impl.js +19 -0
  20. package/dist/src/decorators/rust_impl.js.map +1 -0
  21. package/dist/src/decorators/rust_self.d.ts +3 -0
  22. package/dist/src/decorators/rust_self.js +35 -0
  23. package/dist/src/decorators/rust_self.js.map +1 -0
  24. package/dist/src/emitter.d.ts +2 -11
  25. package/dist/src/emitter.js +7 -1252
  26. package/dist/src/emitter.js.map +1 -1
  27. package/dist/src/formatter/index.d.ts +2 -0
  28. package/dist/src/formatter/index.js +3 -0
  29. package/dist/src/formatter/index.js.map +1 -0
  30. package/dist/src/formatter/mappings.d.ts +4 -0
  31. package/dist/src/formatter/mappings.js +68 -0
  32. package/dist/src/formatter/mappings.js.map +1 -0
  33. package/dist/src/formatter/strings.d.ts +4 -0
  34. package/dist/src/formatter/strings.js +32 -0
  35. package/dist/src/formatter/strings.js.map +1 -0
  36. package/dist/src/generator/etag_router.d.ts +30 -0
  37. package/dist/src/generator/etag_router.js +123 -0
  38. package/dist/src/generator/etag_router.js.map +1 -0
  39. package/dist/src/generator/index.d.ts +5 -0
  40. package/dist/src/generator/index.js +6 -0
  41. package/dist/src/generator/index.js.map +1 -0
  42. package/dist/src/generator/response_enums.d.ts +6 -0
  43. package/dist/src/generator/response_enums.js +58 -0
  44. package/dist/src/generator/response_enums.js.map +1 -0
  45. package/dist/src/generator/router.d.ts +7 -0
  46. package/dist/src/generator/router.js +227 -0
  47. package/dist/src/generator/router.js.map +1 -0
  48. package/dist/src/generator/server_trait.d.ts +6 -0
  49. package/dist/src/generator/server_trait.js +97 -0
  50. package/dist/src/generator/server_trait.js.map +1 -0
  51. package/dist/src/generator/types_file.d.ts +11 -0
  52. package/dist/src/generator/types_file.js +209 -0
  53. package/dist/src/generator/types_file.js.map +1 -0
  54. package/dist/src/index.d.ts +1 -1
  55. package/dist/src/index.js +1 -1
  56. package/dist/src/index.js.map +1 -1
  57. package/dist/src/lib.js +1 -1
  58. package/dist/src/lib.js.map +1 -1
  59. package/dist/src/models/index.d.ts +2 -0
  60. package/dist/src/models/index.js +3 -0
  61. package/dist/src/models/index.js.map +1 -0
  62. package/dist/src/models/keys.d.ts +6 -0
  63. package/dist/src/models/keys.js +8 -0
  64. package/dist/src/models/keys.js.map +1 -0
  65. package/dist/src/models/types.d.ts +45 -0
  66. package/dist/src/models/types.js +2 -0
  67. package/dist/src/models/types.js.map +1 -0
  68. package/dist/src/parser/decorators.d.ts +18 -0
  69. package/dist/src/parser/decorators.js +28 -0
  70. package/dist/src/parser/decorators.js.map +1 -0
  71. package/dist/src/parser/index.d.ts +6 -0
  72. package/dist/src/parser/index.js +7 -0
  73. package/dist/src/parser/index.js.map +1 -0
  74. package/dist/src/parser/operations.d.ts +13 -0
  75. package/dist/src/parser/operations.js +127 -0
  76. package/dist/src/parser/operations.js.map +1 -0
  77. package/dist/src/parser/parameters.d.ts +5 -0
  78. package/dist/src/parser/parameters.js +98 -0
  79. package/dist/src/parser/parameters.js.map +1 -0
  80. package/dist/src/parser/responses.d.ts +13 -0
  81. package/dist/src/parser/responses.js +132 -0
  82. package/dist/src/parser/responses.js.map +1 -0
  83. package/dist/src/parser/routes.d.ts +4 -0
  84. package/dist/src/parser/routes.js +36 -0
  85. package/dist/src/parser/routes.js.map +1 -0
  86. package/dist/src/parser/types.d.ts +9 -0
  87. package/dist/src/parser/types.js +157 -0
  88. package/dist/src/parser/types.js.map +1 -0
  89. package/dist/test/etag_cache.test.d.ts +1 -0
  90. package/dist/test/etag_cache.test.js +62 -0
  91. package/dist/test/etag_cache.test.js.map +1 -0
  92. package/dist/test/hello.test.js +23 -0
  93. package/dist/test/hello.test.js.map +1 -1
  94. package/dist/test/test-host.d.ts +11 -0
  95. package/dist/test/test-host.js +28 -0
  96. package/dist/test/test-host.js.map +1 -1
  97. package/example/main.tsp +48 -1
  98. package/example/output-rust/Cargo.lock +75 -0
  99. package/example/output-rust/Cargo.toml +2 -1
  100. package/example/output-rust/src/generated/server.rs +163 -12
  101. package/example/output-rust/src/generated/types.rs +8 -0
  102. package/example/output-rust/src/main.rs +75 -27
  103. package/justfile +31 -2
  104. package/package.json +1 -1
  105. package/scripts/update-golden.js +36 -0
  106. package/src/decorators/cache_control.ts +14 -0
  107. package/src/decorators/etag_cache.ts +14 -0
  108. package/src/decorators/index.ts +6 -0
  109. package/src/decorators/rust_attr.ts +61 -0
  110. package/src/decorators/rust_derive.ts +55 -0
  111. package/src/decorators/rust_impl.ts +29 -0
  112. package/src/decorators/rust_self.ts +42 -0
  113. package/src/emitter.ts +18 -1623
  114. package/src/formatter/index.ts +2 -0
  115. package/src/formatter/mappings.ts +70 -0
  116. package/src/formatter/strings.ts +33 -0
  117. package/src/generator/etag_router.ts +147 -0
  118. package/src/generator/index.ts +5 -0
  119. package/src/generator/response_enums.ts +76 -0
  120. package/src/generator/router.ts +280 -0
  121. package/src/generator/server_trait.ts +134 -0
  122. package/src/generator/types_file.ts +297 -0
  123. package/src/index.ts +3 -1
  124. package/src/lib.ts +1 -1
  125. package/src/lib.tsp +3 -1
  126. package/src/models/index.ts +2 -0
  127. package/src/models/keys.ts +7 -0
  128. package/src/models/types.ts +54 -0
  129. package/src/parser/decorators.ts +34 -0
  130. package/src/parser/index.ts +6 -0
  131. package/src/parser/operations.ts +158 -0
  132. package/src/parser/parameters.ts +117 -0
  133. package/src/parser/responses.ts +170 -0
  134. package/src/parser/routes.ts +47 -0
  135. package/src/parser/types.ts +215 -0
  136. package/test/etag_cache.test.ts +69 -0
  137. package/test/golden/etag_cache/server.rs +109 -0
  138. package/test/golden/etag_cache/spec.tsp +20 -0
  139. package/test/golden/etag_cache/types.rs +13 -0
  140. package/test/hello.test.ts +24 -0
  141. package/test/test-host.ts +43 -0
package/src/emitter.ts CHANGED
@@ -3,1633 +3,26 @@ import {
3
3
  emitFile,
4
4
  resolvePath,
5
5
  navigateProgram,
6
- getDoc,
7
- isArrayModelType,
8
- isRecordModelType,
9
- getFormat,
10
- getPattern,
11
- Type,
12
6
  Model,
13
- ModelProperty,
14
7
  Enum,
15
8
  Union,
16
9
  Scalar,
17
- Program,
18
- Namespace,
19
- IntrinsicType,
20
- StringLiteral,
21
- DecoratorContext,
22
- getNamespaceFullName,
23
- Operation,
24
- getTags,
25
10
  } from "@typespec/compiler";
26
-
27
- export interface RustEmitterOptions {
28
- moduleName?: string;
29
- }
30
-
31
- interface RustDeriveInfo {
32
- derives: string[];
33
- }
34
-
35
- interface RustAttrInfo {
36
- attrs: string[];
37
- }
38
-
39
- const rustDeriveKey = Symbol("rustDerive");
40
- const rustAttrKey = Symbol("rustAttr");
41
- const rustImplKey = Symbol("rustImpl");
42
- const rustSelfReceiverKey = Symbol("rustSelfReceiver");
43
-
44
- type SelfReceiver = "&self" | "&mut self" | "self";
45
-
46
- interface RustImplInfo {
47
- impl: string;
48
- }
49
-
50
- export function $rustDerive(
51
- context: DecoratorContext,
52
- target: Type,
53
- derive: string,
54
- ) {
55
- if (target.kind !== "Model" && target.kind !== "Enum") {
56
- context.program.reportDiagnostic({
57
- code: "rust-derive-invalid-target",
58
- message: `@rustDerive can only be applied to models and enums`,
59
- severity: "error",
60
- target: context.decoratorTarget,
61
- });
62
- return;
63
- }
64
-
65
- const ns =
66
- target.kind === "Model"
67
- ? target.namespace
68
- ? getNamespaceFullName(target.namespace)
69
- : ""
70
- : target.namespace
71
- ? getNamespaceFullName(target.namespace)
72
- : "";
73
-
74
- if (!ns.startsWith("TypeSpec")) {
75
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
- const info = (target as any)[rustDeriveKey] as RustDeriveInfo | undefined;
77
- if (info) {
78
- if (!info.derives.includes(derive)) {
79
- info.derives.push(derive);
80
- }
81
- } else {
82
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
- (target as any)[rustDeriveKey] = { derives: [derive] };
84
- }
85
- }
86
- }
87
-
88
- export function $rustDerives(
89
- context: DecoratorContext,
90
- target: Type,
91
- ...derives: string[]
92
- ) {
93
- for (const derive of derives) {
94
- $rustDerive(context, target, derive);
95
- }
96
- }
97
-
98
- export function $rustAttr(
99
- context: DecoratorContext,
100
- target: Type,
101
- attr: string,
102
- ) {
103
- if (
104
- target.kind !== "Model" &&
105
- target.kind !== "Enum" &&
106
- target.kind !== "ModelProperty"
107
- ) {
108
- context.program.reportDiagnostic({
109
- code: "rust-attr-invalid-target",
110
- message: `@rustAttr can only be applied to models, enums, and model properties`,
111
- severity: "error",
112
- target: context.decoratorTarget,
113
- });
114
- return;
115
- }
116
-
117
- let ns: Namespace | undefined;
118
- if (target.kind === "Model") {
119
- ns = target.namespace;
120
- } else if (target.kind === "Enum") {
121
- ns = target.namespace;
122
- } else if (target.kind === "ModelProperty") {
123
- ns = target.model?.namespace;
124
- }
125
-
126
- const nsFullName = ns ? getNamespaceFullName(ns) : "";
127
- if (!nsFullName.startsWith("TypeSpec")) {
128
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
- const info = (target as any)[rustAttrKey] as RustAttrInfo | undefined;
130
- if (info) {
131
- if (!info.attrs.includes(attr)) {
132
- info.attrs.push(attr);
133
- }
134
- } else {
135
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
136
- (target as any)[rustAttrKey] = { attrs: [attr] };
137
- }
138
- }
139
- }
140
-
141
- export function $rustAttrs(
142
- context: DecoratorContext,
143
- target: Type,
144
- ...attrs: string[]
145
- ) {
146
- for (const attr of attrs) {
147
- $rustAttr(context, target, attr);
148
- }
149
- }
150
-
151
- export function $rustImpl(
152
- context: DecoratorContext,
153
- target: Type,
154
- impl: string,
155
- ) {
156
- if (target.kind !== "Model") {
157
- context.program.reportDiagnostic({
158
- code: "rust-impl-invalid-target",
159
- message: `@rustImpl can only be applied to models`,
160
- severity: "error",
161
- target: context.decoratorTarget,
162
- });
163
- return;
164
- }
165
-
166
- const ns = target.namespace ? getNamespaceFullName(target.namespace) : "";
167
-
168
- if (!ns.startsWith("TypeSpec")) {
169
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
170
- (target as any)[rustImplKey] = { impl: impl };
171
- }
172
- }
173
-
174
- export function $rustMut(context: DecoratorContext, target: Type) {
175
- if (target.kind !== "Operation") {
176
- context.program.reportDiagnostic({
177
- code: "rust-mut-invalid-target",
178
- message: `@rustMut can only be applied to operations`,
179
- severity: "error",
180
- target: context.decoratorTarget,
181
- });
182
- return;
183
- }
184
-
185
- const ns = target.namespace ? getNamespaceFullName(target.namespace) : "";
186
- if (!ns.startsWith("TypeSpec")) {
187
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
188
- (target as any)[rustSelfReceiverKey] = "&mut self";
189
- }
190
- }
191
-
192
- export function $rustOwn(context: DecoratorContext, target: Type) {
193
- if (target.kind !== "Operation") {
194
- context.program.reportDiagnostic({
195
- code: "rust-own-invalid-target",
196
- message: `@rustOwn can only be applied to operations`,
197
- severity: "error",
198
- target: context.decoratorTarget,
199
- });
200
- return;
201
- }
202
-
203
- const ns = target.namespace ? getNamespaceFullName(target.namespace) : "";
204
- if (!ns.startsWith("TypeSpec")) {
205
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
206
- (target as any)[rustSelfReceiverKey] = "self";
207
- }
208
- }
209
-
210
- type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
211
-
212
- interface OperationInfo {
213
- name: string;
214
- method: HttpMethod;
215
- path: string;
216
- tags: string[];
217
- parameters: ParameterInfo[];
218
- body: ModelProperty | undefined;
219
- responses: ResponseInfo[];
220
- doc: string | undefined;
221
- }
222
-
223
- interface ParameterInfo {
224
- name: string;
225
- rustName: string;
226
- rustType: string;
227
- location: "path" | "query" | "header" | "cookie";
228
- required: boolean;
229
- optional?: boolean;
230
- }
231
-
232
- interface ResponseInfo {
233
- statusCode: number;
234
- bodyType: string | undefined;
235
- bodyDescription: string | undefined;
236
- isSse?: boolean;
237
- }
238
-
239
- function getDecoratorName(decorator: {
240
- node?: { target?: { sv?: string; kind?: string } };
241
- }): string {
242
- if (!decorator) return "";
243
- if (typeof decorator !== "object") return "";
244
-
245
- if (decorator.node?.target?.sv) {
246
- return decorator.node.target.sv;
247
- }
248
- if (
249
- decorator.node?.target?.kind === "Identifier" &&
250
- decorator.node?.target?.sv
251
- ) {
252
- return decorator.node.target.sv;
253
- }
254
-
255
- return "";
256
- }
257
-
258
- function getDecoratorArgValue(
259
- decorator: {
260
- args?: { jsValue?: unknown; value?: unknown }[];
261
- arguments?: { jsValue?: unknown; value?: unknown }[];
262
- },
263
- index: number = 0,
264
- ): string {
265
- if (!decorator) return "";
266
- const args = decorator.args || decorator.arguments;
267
- if (!args) return "";
268
- const arg = args[index];
269
- if (arg?.jsValue !== undefined) return String(arg.jsValue);
270
- if (arg?.value !== undefined) return String(arg.value);
271
- return "";
272
- }
273
-
274
- function getHttpMethod(
275
- _program: Program,
276
- operation: Operation,
277
- ): HttpMethod | undefined {
278
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
279
- const decorators = (operation as any).decorators;
280
- if (!decorators) return undefined;
281
-
282
- for (const key of Object.keys(decorators)) {
283
- const decorator = decorators[key];
284
- const name = getDecoratorName(decorator);
285
- if (name === "get") return "GET";
286
- if (name === "post") return "POST";
287
- if (name === "put") return "PUT";
288
- if (name === "patch") return "PATCH";
289
- if (name === "delete") return "DELETE";
290
- if (name === "head") return "HEAD";
291
- }
292
- return undefined;
293
- }
294
-
295
- function getRoute(_program: Program, target: Namespace | Operation): string {
296
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
297
- const decorators = (target as any).decorators;
298
- if (!decorators) return "";
299
-
300
- for (const key of Object.keys(decorators)) {
301
- const decorator = decorators[key];
302
- const name = getDecoratorName(decorator);
303
- if (name === "route") {
304
- return getDecoratorArgValue(decorator, 0);
305
- }
306
- }
307
- return "";
308
- }
309
-
310
- function getFullRoute(program: Program, ns: Namespace): string {
311
- const routes: string[] = [];
312
- let current: Namespace | undefined = ns;
313
-
314
- while (current) {
315
- const route = getRoute(program, current);
316
- if (route) {
317
- routes.unshift(route);
318
- }
319
- current = current.namespace;
320
- }
321
-
322
- return routes.join("");
323
- }
324
-
325
- function hasAuthDecorator(operation: Operation): boolean {
326
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
327
- const decorators = (operation as any).decorators;
328
- if (!decorators) return false;
329
-
330
- for (const key of Object.keys(decorators)) {
331
- const decorator = decorators[key];
332
- const name = getDecoratorName(decorator);
333
- if (name === "useAuth") {
334
- return true;
335
- }
336
- }
337
- return false;
338
- }
339
-
340
- function getSelfReceiver(operation: Operation): SelfReceiver {
341
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
342
- const receiver = (operation as any)[rustSelfReceiverKey] as
343
- | SelfReceiver
344
- | undefined;
345
- return receiver ?? "&self";
346
- }
347
-
348
- function getOperationParameters(
349
- program: Program,
350
- operation: Operation,
351
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
352
- ): ParameterInfo[] {
353
- const params: ParameterInfo[] = [];
354
- const model = operation.parameters;
355
-
356
- for (const [propName, prop] of model.properties) {
357
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
358
- const decorators = (prop as any).decorators;
359
-
360
- // Skip body parameters - they are handled separately
361
- let isBody = false;
362
- if (decorators) {
363
- for (const key of Object.keys(decorators)) {
364
- const decorator = decorators[key];
365
- const name = getDecoratorName(decorator);
366
- if (name === "body" || name === "bodyRoot") {
367
- isBody = true;
368
- break;
369
- }
370
- }
371
- }
372
- if (isBody) continue;
373
-
374
- let location: "path" | "query" | "header" | "cookie" = "query";
375
- let rustName = toRustIdent(propName);
376
-
377
- if (decorators) {
378
- for (const key of Object.keys(decorators)) {
379
- const decorator = decorators[key];
380
- const name = getDecoratorName(decorator);
381
- if (name === "path") {
382
- location = "path";
383
- break;
384
- } else if (name === "query") {
385
- location = "query";
386
- break;
387
- } else if (name === "header") {
388
- location = "header";
389
- const headerVal = getDecoratorArgValue(decorator, 0);
390
- if (headerVal) {
391
- rustName = toRustIdent(headerVal);
392
- }
393
- break;
394
- } else if (name === "cookie") {
395
- location = "cookie";
396
- break;
397
- }
398
- }
399
- }
400
-
401
- const { type: rustType } = getRustTypeForProperty(
402
- prop.type,
403
- program,
404
- anonymousEnums,
405
- );
406
-
407
- params.push({
408
- name: propName,
409
- rustName,
410
- rustType,
411
- location,
412
- required: !prop.optional,
413
- optional: prop.optional,
414
- });
415
- }
416
-
417
- return params;
418
- }
419
-
420
- function getOperationBody(operation: Operation): ModelProperty | undefined {
421
- for (const [_propName, prop] of operation.parameters.properties) {
422
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
423
- const decorators = (prop as any).decorators;
424
- if (!decorators) continue;
425
-
426
- for (const key of Object.keys(decorators)) {
427
- const decorator = decorators[key];
428
- const name = getDecoratorName(decorator);
429
- if (name === "body" || name === "bodyRoot") {
430
- return prop;
431
- }
432
- }
433
- }
434
- return undefined;
435
- }
436
-
437
- function getOperationResponses(
438
- program: Program,
439
- operation: Operation,
440
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
441
- ): ResponseInfo[] {
442
- const responses: ResponseInfo[] = [];
443
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
444
- const returnType = operation.returnType as any;
445
-
446
- // Check for Array return type first (use runtime check since TS doesn't narrow Array)
447
- if (
448
- returnType.kind !== "Union" &&
449
- returnType.kind !== "Model" &&
450
- returnType.valueType
451
- ) {
452
- // This is an Array type
453
- const { type: rustType } = getRustTypeForProperty(
454
- returnType.valueType,
455
- program,
456
- anonymousEnums,
457
- );
458
- responses.push({
459
- statusCode: 200,
460
- bodyType: rustType,
461
- bodyDescription: "",
462
- });
463
- return responses;
464
- }
465
-
466
- if (returnType.kind === "Union") {
467
- const union = returnType as Union;
468
- for (const variant of union.variants.values()) {
469
- const statusCode = getStatusCode(variant);
470
- const bodyInfo = getBodyFromResponse(variant, program, anonymousEnums);
471
- responses.push({
472
- statusCode,
473
- bodyType: bodyInfo.type,
474
- bodyDescription: bodyInfo.description,
475
- isSse: bodyInfo.isSse,
476
- });
477
- }
478
- } else if (returnType.kind === "Model") {
479
- const model = returnType as Model;
480
- if (model.name === "SSEStream") {
481
- responses.push({
482
- statusCode: 200,
483
- bodyType: "axum::response::Response",
484
- bodyDescription: "Server-Sent Events stream",
485
- isSse: true,
486
- });
487
- return responses;
488
- }
489
- let foundStatusCode = false;
490
- for (const [propName, prop] of model.properties) {
491
- if (propName === "body") {
492
- const { type: rustType } = getRustTypeForProperty(
493
- prop.type,
494
- program,
495
- anonymousEnums,
496
- );
497
- responses.push({
498
- statusCode: 200,
499
- bodyType: rustType,
500
- bodyDescription: getDoc(program, prop),
501
- });
502
- } else if (propName === "statusCode") {
503
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
504
- const typeAny = prop.type as any;
505
- if (typeAny.value !== undefined) {
506
- const statusCode = typeAny.value as number;
507
- responses.push({
508
- statusCode,
509
- bodyType: undefined,
510
- bodyDescription: undefined,
511
- });
512
- foundStatusCode = true;
513
- }
514
- }
515
- }
516
- if (!foundStatusCode && responses.length === 0) {
517
- responses.push({
518
- statusCode: 200,
519
- bodyType: undefined,
520
- bodyDescription: undefined,
521
- });
522
- }
523
- }
524
-
525
- return responses;
526
- }
527
-
528
- function getStatusCode(variant: { type: Type }): number {
529
- if (variant.type.kind === "Model") {
530
- const model = variant.type as Model;
531
- for (const [propName, prop] of model.properties) {
532
- if (propName === "statusCode") {
533
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
534
- const typeAny = prop.type as any;
535
- if (typeAny.value !== undefined) {
536
- return typeAny.value as number;
537
- }
538
- }
539
- }
540
- }
541
- return 200;
542
- }
543
-
544
- function getBodyFromResponse(
545
- variant: { type: Type },
546
- program: Program,
547
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
548
- ): {
549
- type: string | undefined;
550
- description: string | undefined;
551
- isSse?: boolean;
552
- } {
553
- if (variant.type.kind === "Model") {
554
- const model = variant.type as Model;
555
- if (model.name === "SSEStream") {
556
- return {
557
- type: "axum::response::Response",
558
- description: "Server-Sent Events stream",
559
- isSse: true,
560
- };
561
- }
562
- for (const [_propName, prop] of model.properties) {
563
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
564
- const decorators = (prop as any).decorators;
565
- let isBody = false;
566
- if (decorators) {
567
- for (const key of Object.keys(decorators)) {
568
- const decorator = decorators[key];
569
- const name = getDecoratorName(decorator);
570
- if (name === "body" || name === "bodyRoot") {
571
- isBody = true;
572
- break;
573
- }
574
- }
575
- }
576
- if (isBody) {
577
- const { type: rustType } = getRustTypeForProperty(
578
- prop.type,
579
- program,
580
- anonymousEnums,
581
- );
582
- return { type: rustType, description: getDoc(program, prop) };
583
- }
584
- }
585
- }
586
- return { type: undefined, description: undefined };
587
- }
588
-
589
- function getAllOperations(
590
- program: Program,
591
- ): { namespace: Namespace; operations: Operation[] }[] {
592
- const seenNamespaces = new Set<string>();
593
- const namespaceOps = new Map<string, { ns: Namespace; ops: Operation[] }>();
594
-
595
- navigateProgram(program, {
596
- namespace(ns: Namespace) {
597
- const route = getRoute(program, ns);
598
- if (!route) return;
599
- const fullName = getNamespaceFullName(ns);
600
- if (!seenNamespaces.has(fullName)) {
601
- seenNamespaces.add(fullName);
602
- namespaceOps.set(fullName, { ns, ops: [] });
603
- }
604
- },
605
- operation(op: Operation) {
606
- const method = getHttpMethod(program, op);
607
- if (!method) return;
608
- const ns = op.namespace;
609
- if (!ns) return;
610
- const fullName = getNamespaceFullName(ns);
611
- if (!seenNamespaces.has(fullName)) {
612
- seenNamespaces.add(fullName);
613
- namespaceOps.set(fullName, { ns, ops: [] });
614
- }
615
- const entry = namespaceOps.get(fullName);
616
- if (entry) {
617
- entry.ops.push(op);
618
- }
619
- },
620
- });
621
-
622
- const result: { namespace: Namespace; operations: Operation[] }[] = [];
623
- for (const [, entry] of namespaceOps) {
624
- if (entry.ops.length > 0) {
625
- result.push({ namespace: entry.ns, operations: entry.ops });
626
- }
627
- }
628
- return result;
629
- }
630
-
631
- function buildFullPath(namespaceRoute: string, operationRoute: string): string {
632
- let fullPath = namespaceRoute + operationRoute;
633
- fullPath = fullPath.replace(/\/+/g, "/");
634
- if (fullPath.length > 1 && fullPath.endsWith("/")) {
635
- fullPath = fullPath.slice(0, -1);
636
- }
637
- return fullPath;
638
- }
639
-
640
- function emitOperationInfo(
641
- program: Program,
642
- op: Operation,
643
- nsRoute: string,
644
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
645
- ): OperationInfo | undefined {
646
- const method = getHttpMethod(program, op);
647
- if (!method) return undefined;
648
-
649
- const opRoute = getRoute(program, op);
650
- const fullPath = buildFullPath(nsRoute, opRoute);
651
- const tags = getTags(program, op) ?? [];
652
- const params = getOperationParameters(program, op, anonymousEnums);
653
- const body = getOperationBody(op);
654
- const responses = getOperationResponses(program, op, anonymousEnums);
655
- const doc = getDoc(program, op);
656
-
657
- const opName = op.name.replace(/[^a-zA-Z0-9_]/g, "_");
658
-
659
- return {
660
- name: opName,
661
- method,
662
- path: fullPath,
663
- tags,
664
- parameters: params,
665
- body: body,
666
- responses,
667
- doc,
668
- };
669
- }
670
-
671
- function getStatusVariantName(statusCode: number): string {
672
- const statusNames: Record<number, string> = {
673
- 200: "Ok",
674
- 201: "Created",
675
- 202: "Accepted",
676
- 204: "NoContent",
677
- 400: "BadRequest",
678
- 401: "Unauthorized",
679
- 403: "Forbidden",
680
- 404: "NotFound",
681
- 409: "Conflict",
682
- 500: "InternalServerError",
683
- };
684
- return statusNames[statusCode] || `Status${statusCode}`;
685
- }
686
-
687
- function getHttpStatusCode(statusCode: number): string {
688
- const statusCodes: Record<number, string> = {
689
- 200: "StatusCode::OK",
690
- 201: "StatusCode::CREATED",
691
- 202: "StatusCode::ACCEPTED",
692
- 204: "StatusCode::NO_CONTENT",
693
- 400: "StatusCode::BAD_REQUEST",
694
- 401: "StatusCode::UNAUTHORIZED",
695
- 403: "StatusCode::FORBIDDEN",
696
- 404: "StatusCode::NOT_FOUND",
697
- 409: "StatusCode::CONFLICT",
698
- 500: "StatusCode::INTERNAL_SERVER_ERROR",
699
- };
700
- return statusCodes[statusCode] || `StatusCode::from_u16(${statusCode})`;
701
- }
702
-
703
- function generateServerTrait(
704
- program: Program,
705
- namespaceGroups: { namespace: Namespace; operations: Operation[] }[],
706
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
707
- ): string {
708
- const parts: string[] = [];
709
-
710
- parts.push(`use super::types::*;
711
- use async_trait::async_trait;
712
- use axum::extract::Path;
713
- use axum::Extension;
714
- use axum::http::StatusCode;
715
- use axum::response::IntoResponse;
716
- use axum::Json;
717
- use eyre::Result;
718
-
719
- #[async_trait]
720
- pub trait Server: Send + Sync {
721
- type Claims: Send + Sync + 'static;
722
-
723
- `);
724
-
725
- for (const group of namespaceGroups) {
726
- const nsName = toPascalCase(
727
- group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"),
728
- );
729
-
730
- for (const op of group.operations) {
731
- const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
732
- if (!opInfo) continue;
733
-
734
- if (opInfo.doc) {
735
- parts.push(` ${formatDoc(opInfo.doc)}`);
736
- }
737
-
738
- const responseName = `${nsName}${toPascalCase(opInfo.name)}Response`;
739
- const fnName = toRustIdent(`${nsName}_${opInfo.name}`);
740
- const isProtected = hasAuthDecorator(op);
741
-
742
- // Build parameter list for the trait method
743
- const paramParts: string[] = [];
744
-
745
- // Add path parameters
746
- for (const param of opInfo.parameters) {
747
- if (param.location === "path") {
748
- paramParts.push(`${param.rustName}: ${param.rustType}`);
749
- }
750
- }
751
-
752
- // Add query parameters
753
- for (const param of opInfo.parameters) {
754
- if (param.location === "query") {
755
- paramParts.push(`${param.rustName}: ${param.rustType}`);
756
- }
757
- }
758
-
759
- // Add body parameter
760
- if (opInfo.body) {
761
- const bodyType = getRustTypeForProperty(
762
- opInfo.body.type,
763
- program,
764
- anonymousEnums,
765
- );
766
- paramParts.push(`body: ${bodyType.type}`);
767
- }
768
-
769
- const paramsStr = paramParts.join(", ");
770
- const selfReceiver = getSelfReceiver(op);
771
-
772
- if (isProtected) {
773
- if (paramsStr) {
774
- parts.push(
775
- ` async fn ${fnName}(${selfReceiver}, claims: Self::Claims, ${paramsStr}) -> Result<${responseName}>;`,
776
- );
777
- } else {
778
- parts.push(
779
- ` async fn ${fnName}(${selfReceiver}, claims: Self::Claims) -> Result<${responseName}>;`,
780
- );
781
- }
782
- } else {
783
- if (paramsStr) {
784
- parts.push(
785
- ` async fn ${fnName}(${selfReceiver}, ${paramsStr}) -> Result<${responseName}>;`,
786
- );
787
- } else {
788
- parts.push(
789
- ` async fn ${fnName}(${selfReceiver}) -> Result<${responseName}>;`,
790
- );
791
- }
792
- }
793
- }
794
- }
795
-
796
- parts.push("}");
797
-
798
- return parts.join("\n");
799
- }
800
-
801
- function generateResponseEnums(
802
- program: Program,
803
- namespaceGroups: { namespace: Namespace; operations: Operation[] }[],
804
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
805
- ): string {
806
- const parts: string[] = [];
807
-
808
- for (const group of namespaceGroups) {
809
- const nsName = toPascalCase(
810
- group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"),
811
- );
812
-
813
- for (const op of group.operations) {
814
- const opInfo = emitOperationInfo(program, op, "", anonymousEnums);
815
- if (!opInfo) continue;
816
-
817
- if (opInfo.responses.length === 0) continue;
818
-
819
- const responseName = `${nsName}${toPascalCase(opInfo.name)}Response`;
820
-
821
- const variants: string[] = [];
822
- for (const resp of opInfo.responses) {
823
- const variantName = getStatusVariantName(resp.statusCode);
824
- if (!resp.bodyType) {
825
- variants.push(` ${variantName},`);
826
- } else if (resp.isSse) {
827
- variants.push(` ${variantName}(${resp.bodyType}),`);
828
- } else {
829
- variants.push(` ${variantName}(Json<${resp.bodyType}>),`);
830
- }
831
- }
832
- parts.push(`#[allow(clippy::type_complexity)]
833
- pub enum ${responseName} {
834
- ${variants.join("\n")}
835
- }
836
- `);
837
-
838
- parts.push(`impl IntoResponse for ${responseName} {
839
- fn into_response(self) -> axum::response::Response {
840
- match self {
841
- `);
842
- for (const resp of opInfo.responses) {
843
- const variantName = getStatusVariantName(resp.statusCode);
844
- const statusCodeStr = getHttpStatusCode(resp.statusCode);
845
- if (!resp.bodyType) {
846
- parts.push(
847
- ` ${responseName}::${variantName} => ${statusCodeStr}.into_response(),`,
848
- );
849
- } else if (resp.isSse) {
850
- parts.push(
851
- ` ${responseName}::${variantName}(body) => body.into_response(),`,
852
- );
853
- } else {
854
- parts.push(
855
- ` ${responseName}::${variantName}(body) => (${statusCodeStr}, body).into_response(),`,
856
- );
857
- }
858
- }
859
- parts.push(` }
860
- }
861
- }
862
- `);
863
- }
864
- }
865
-
866
- return parts.join("\n");
867
- }
868
-
869
- function generateRouter(
870
- program: Program,
871
- namespaceGroups: { namespace: Namespace; operations: Operation[] }[],
872
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
873
- ): string {
874
- const handlers: string[] = [];
875
- const queryTypeStructs: string[] = [];
876
- const publicRoutes: string[] = [];
877
- const protectedRoutes: string[] = [];
878
- const usedMethods = new Set<string>();
879
-
880
- for (const group of namespaceGroups) {
881
- const nsRoute = getFullRoute(program, group.namespace);
882
- if (!nsRoute) continue;
883
-
884
- const nsName = toPascalCase(
885
- group.namespace.name.replace(/[^a-zA-Z0-9_]/g, "_"),
886
- );
887
-
888
- for (const op of group.operations) {
889
- const opInfo = emitOperationInfo(program, op, nsRoute, anonymousEnums);
890
- if (!opInfo) continue;
891
-
892
- const method = opInfo.method.toLowerCase();
893
- usedMethods.add(method);
894
-
895
- const handlerFnName = toRustIdent(`${nsName}_${opInfo.name}`);
896
- const traitFnName = handlerFnName;
897
- const isProtected = hasAuthDecorator(op);
898
- const selfReceiver = getSelfReceiver(op);
899
-
900
- const pathParams = opInfo.parameters.filter((p) => p.location === "path");
901
- const hasPathParams = pathParams.length > 0;
902
- const queryParams = opInfo.parameters.filter(
903
- (p) => p.location === "query",
904
- );
905
- const hasQueryParams = queryParams.length > 0;
906
- const hasBody = !!opInfo.body;
907
-
908
- // Build extractor lines and server method call arguments
909
- // IMPORTANT: axum requires specific extractor order:
910
- // State -> Extension -> Path -> Query -> Json -> Body
911
- const extractorLines: string[] = [];
912
- const serverArgs: string[] = [];
913
-
914
- // State is always first (added in handler template)
915
- const serviceBinding =
916
- selfReceiver === "&mut self" ? "mut service" : "service";
917
-
918
- // Extension (claims) comes after State
919
- if (isProtected) {
920
- extractorLines.push(` Extension(claims): Extension<S::Claims>,`);
921
- serverArgs.push(`claims`);
922
- }
923
-
924
- // Path params come after Extension
925
- if (hasPathParams) {
926
- const pathTypes = pathParams.map((p) => p.rustType).join(", ");
927
- const pathFields = pathParams.map((p) => p.rustName).join(", ");
928
- if (pathParams.length === 1) {
929
- extractorLines.push(` Path(${pathFields}): Path<${pathTypes}>,`);
930
- } else {
931
- extractorLines.push(
932
- ` Path((${pathFields})): Path<(${pathTypes})>,`,
933
- );
934
- }
935
- // Add path params to server method args
936
- for (const param of pathParams) {
937
- serverArgs.push(param.rustName);
938
- }
939
- }
940
-
941
- // Query params come after Path
942
- if (hasQueryParams && queryParams.length > 0) {
943
- const queryTypeName = `${toPascalCase(handlerFnName)}Query`;
944
- const queryFields = queryParams
945
- .map(
946
- (p) =>
947
- ` #[serde(rename = "${p.name}")]\n pub ${p.rustName}: ${p.rustType}`,
948
- )
949
- .join(",\n");
950
- queryTypeStructs.push(
951
- `#[derive(Debug, Clone, serde::Deserialize)]\npub struct ${queryTypeName} {\n${queryFields}\n}`,
952
- );
953
- extractorLines.push(` Query(params): Query<${queryTypeName}>,`);
954
- for (const param of queryParams) {
955
- serverArgs.push(`params.${param.rustName}`);
956
- }
957
- }
958
-
959
- // Json body comes last
960
- if (hasBody && opInfo.body) {
961
- const bodyType = getRustTypeForProperty(
962
- opInfo.body.type,
963
- program,
964
- anonymousEnums,
965
- );
966
- extractorLines.push(` Json(payload): Json<${bodyType.type}>,`);
967
- serverArgs.push(`payload`);
968
- }
969
-
970
- // Build server method call
971
- const serverArgsStr = serverArgs.join(", ");
972
- const serverCall = `service.${traitFnName}(${serverArgsStr}).await`;
973
-
974
- // All handlers use <S> generics, Claims is now an associated type
975
- // For &mut self, we need Clone because service is extracted multiple times
976
- // For self, we can't use Clone (would need Arc/Mutex or different pattern)
977
- const needsClone = selfReceiver !== "self" ? "+ Clone" : "";
978
- const handlerCode =
979
- selfReceiver === "self"
980
- ? `// NOTE: ${handlerFnName} takes self and cannot be used with the router pattern.
981
- // It consumes the service, so you need to implement your own handler pattern.
982
- pub async fn ${handlerFnName}_handler<S>(
983
- axum::extract::State(service): axum::extract::State<S>,
984
- ${extractorLines.join("\n")}
985
- ) -> impl axum::response::IntoResponse
986
- where
987
- S: Server + Send + Sync + 'static,
988
- S::Claims: Send + Sync + Clone + 'static,
989
- {
990
- let result = service.${traitFnName}(${serverArgsStr}).await;
991
- match result {
992
- Ok(response) => response.into_response(),
993
- Err(e) => (
994
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
995
- format!("Internal error: {e}"),
996
- )
997
- .into_response(),
998
- }
999
- }`
1000
- : `pub async fn ${handlerFnName}_handler<S>(
1001
- axum::extract::State(${serviceBinding}): axum::extract::State<S>,
1002
- ${extractorLines.join("\n")}
1003
- ) -> impl axum::response::IntoResponse
1004
- where
1005
- S: Server${needsClone} + Send + Sync + 'static,
1006
- S::Claims: Send + Sync + Clone + 'static,
1007
- {
1008
- let result = ${serverCall};
1009
- match result {
1010
- Ok(response) => response.into_response(),
1011
- Err(e) => (
1012
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
1013
- format!("Internal error: {e}"),
1014
- )
1015
- .into_response(),
1016
- }
1017
- }`;
1018
-
1019
- handlers.push(handlerCode);
1020
-
1021
- // Don't add routes for self methods (they consume the service)
1022
- if (selfReceiver === "self") {
1023
- continue;
1024
- }
1025
-
1026
- const routePath = `"${opInfo.path}"`;
1027
- let routeStmt = "";
1028
- if (isProtected) {
1029
- routeStmt = `.route(${routePath}, ${method}(${handlerFnName}_handler::<S>))`;
1030
- protectedRoutes.push(routeStmt);
1031
- } else {
1032
- routeStmt = `.route(${routePath}, ${method}(${handlerFnName}_handler::<S>))`;
1033
- publicRoutes.push(routeStmt);
1034
- }
1035
- }
1036
- }
1037
-
1038
- const methodImports = Array.from(usedMethods).sort().join(", ");
1039
-
1040
- const routerBody = buildRouterBody(publicRoutes, protectedRoutes);
1041
-
1042
- const parts: string[] = [];
1043
- parts.push(`use axum::extract::Query;
1044
- use axum::routing::{${methodImports}};
1045
- use axum::Router;
1046
-
1047
- `);
1048
- if (queryTypeStructs.length > 0) {
1049
- parts.push(queryTypeStructs.join("\n\n"));
1050
- parts.push("\n\n");
1051
- }
1052
- parts.push(handlers.join("\n\n"));
1053
- parts.push(`
1054
- pub fn create_router<S, M>(service: S, middleware: M) -> Router
1055
- where
1056
- S: Server + Clone + Send + Sync + 'static,
1057
- S::Claims: Send + Sync + Clone + 'static,
1058
- M: FnOnce(Router<S>) -> Router<S> + Clone + Send + Sync + 'static,
1059
- {
1060
- ${routerBody}
1061
- }`);
1062
-
1063
- return parts.join("\n");
1064
- }
1065
-
1066
- function buildRouterBody(
1067
- publicRoutes: string[],
1068
- protectedRoutes: string[],
1069
- ): string {
1070
- const lines: string[] = [];
1071
- lines.push(" let mut router = Router::new();");
1072
- if (publicRoutes.length > 0) {
1073
- lines.push(" let public = Router::new()");
1074
- for (const r of publicRoutes) {
1075
- lines.push(` ${r.trim()}`);
1076
- }
1077
- lines.push(" ;");
1078
- lines.push(" router = router.merge(public);");
1079
- }
1080
- if (protectedRoutes.length > 0) {
1081
- lines.push(" let protected = Router::new()");
1082
- for (const r of protectedRoutes) {
1083
- lines.push(` ${r.trim()}`);
1084
- }
1085
- lines.push(" ;");
1086
- lines.push(" router = router.merge(middleware(protected));");
1087
- }
1088
- lines.push(" router.with_state(service)");
1089
- return lines.join("\n");
1090
- }
1091
-
1092
- const scalarToRust: Record<string, string> = {
1093
- string: "String",
1094
- int8: "i8",
1095
- int16: "i16",
1096
- int32: "i32",
1097
- int64: "i64",
1098
- uint8: "u8",
1099
- uint16: "u16",
1100
- uint32: "u32",
1101
- uint64: "u64",
1102
- float32: "f32",
1103
- float64: "f64",
1104
- boolean: "bool",
1105
- bytes: "Vec<u8>",
1106
- plainDate: "chrono::NaiveDate",
1107
- plainTime: "chrono::NaiveTime",
1108
- utcDateTime: "chrono::DateTime<chrono::Utc>",
1109
- offsetDateTime: "chrono::DateTime<chrono::FixedOffset>",
1110
- plainDateTime: "chrono::NaiveDateTime",
1111
- duration: "String",
1112
- numeric: "f64",
1113
- integer: "i64",
1114
- float: "f64",
1115
- safeint: "i64",
1116
- decimal: "f64",
1117
- decimal128: "f64",
1118
- url: "String",
1119
- };
1120
-
1121
- const formatToRust: Record<string, string> = {
1122
- uuid: "uuid::Uuid",
1123
- date: "chrono::NaiveDate",
1124
- time: "chrono::NaiveTime",
1125
- dateTime: "chrono::DateTime<chrono::Utc>",
1126
- "date-time": "chrono::DateTime<chrono::Utc>",
1127
- };
1128
-
1129
- const typeSpecNamespaces = new Set([
1130
- "TypeSpec",
1131
- "@typespec/http",
1132
- "@typespec/rest",
1133
- "@typespec/openapi",
1134
- "@typespec/openapi3",
1135
- "@typespec/json-schema",
1136
- ]);
1137
-
1138
- function isStdLibNamespace(ns: Namespace | undefined): boolean {
1139
- if (!ns) return false;
1140
- const fullName = ns.name;
1141
- if (typeSpecNamespaces.has(fullName)) return true;
1142
- if (ns.namespace) return isStdLibNamespace(ns.namespace);
1143
- return false;
1144
- }
1145
-
1146
- function isStdLibType(type: Type): boolean {
1147
- if ("namespace" in type) {
1148
- const ns = (type as Model | Enum | Union | Scalar).namespace;
1149
- if (isStdLibNamespace(ns as Namespace)) return true;
1150
- }
1151
- return false;
1152
- }
1153
-
1154
- interface AnonymousStringLiteralUnion {
1155
- enumName: string;
1156
- variants: StringLiteral[];
1157
- }
1158
-
1159
- function getRustTypeForProperty(
1160
- type: Type,
1161
- program: Program,
1162
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
1163
- ): { type: string; isStringLiteral: boolean; stringLiteralValue?: string } {
1164
- const kind = type.kind as string;
1165
-
1166
- if (kind === "Model") {
1167
- const model = type as Model;
1168
- if (isArrayModelType(model) && model.indexer?.value) {
1169
- const element = getRustTypeForProperty(
1170
- model.indexer.value,
1171
- program,
1172
- anonymousEnums,
1173
- );
1174
- return { type: `Vec<${element.type}>`, isStringLiteral: false };
1175
- }
1176
- if (isRecordModelType(model) && model.indexer?.value) {
1177
- const value = getRustTypeForProperty(
1178
- model.indexer.value,
1179
- program,
1180
- anonymousEnums,
1181
- );
1182
- return {
1183
- type: `std::collections::HashMap<String, ${value.type}>`,
1184
- isStringLiteral: false,
1185
- };
1186
- }
1187
- return { type: toPascalCase(model.name), isStringLiteral: false };
1188
- }
1189
-
1190
- if (kind === "ModelProperty") {
1191
- return getRustTypeForProperty(
1192
- (type as ModelProperty).type,
1193
- program,
1194
- anonymousEnums,
1195
- );
1196
- }
1197
-
1198
- if (kind === "Enum") {
1199
- return { type: toPascalCase((type as Enum).name), isStringLiteral: false };
1200
- }
1201
-
1202
- if (kind === "Union") {
1203
- const unionType = type as Union;
1204
- const variants = Array.from(unionType.variants.values());
1205
- const allStringLiterals = variants.every((v) => v.type.kind === "String");
1206
-
1207
- if (allStringLiterals) {
1208
- if (unionType.name) {
1209
- return {
1210
- type: toPascalCase(unionType.name),
1211
- isStringLiteral: false,
1212
- };
1213
- }
1214
- const values = variants.map((v) => (v.type as StringLiteral).value);
1215
- const sanitized = values.map((v) => v.replace(/_/g, ""));
1216
- const firstTwo = sanitized.slice(0, 2).map(toPascalCase).join("");
1217
- const enumName = `Enum${firstTwo}${sanitized.length}`;
1218
- if (!anonymousEnums.has(enumName)) {
1219
- anonymousEnums.set(enumName, {
1220
- enumName,
1221
- variants: variants.map((v) => v.type as StringLiteral),
1222
- });
1223
- }
1224
- return { type: enumName, isStringLiteral: false };
1225
- }
1226
-
1227
- const nonNullVariants = variants.filter((v) => {
1228
- const vt = v.type;
1229
- if ((vt.kind as string) === "Null") return false;
1230
- if (
1231
- (vt.kind as string) === "Intrinsic" &&
1232
- (vt as IntrinsicType).name === "null"
1233
- )
1234
- return false;
1235
- return true;
1236
- });
1237
-
1238
- if (
1239
- nonNullVariants.length === 1 &&
1240
- (variants.length === 2 ||
1241
- variants.some((v) => {
1242
- const vt = v.type;
1243
- return (
1244
- (vt.kind as string) === "Null" ||
1245
- ((vt.kind as string) === "Intrinsic" &&
1246
- (vt as IntrinsicType).name === "null")
1247
- );
1248
- }))
1249
- ) {
1250
- const vt = getRustTypeForProperty(
1251
- nonNullVariants[0].type,
1252
- program,
1253
- anonymousEnums,
1254
- );
1255
- return { type: `Option<${vt.type}>`, isStringLiteral: false };
1256
- }
1257
-
1258
- const variantStrings: string[] = [];
1259
- for (const v of variants) {
1260
- const vt = v.type;
1261
- if ((vt.kind as string) === "Null") continue;
1262
- if (
1263
- (vt.kind as string) === "Intrinsic" &&
1264
- (vt as IntrinsicType).name === "null"
1265
- )
1266
- continue;
1267
- const rustVt = getRustTypeForProperty(vt, program, anonymousEnums);
1268
- variantStrings.push(rustVt.type);
1269
- }
1270
- const uniqueTypes = [...new Set(variantStrings)];
1271
- const resultType =
1272
- uniqueTypes.length === 1
1273
- ? uniqueTypes[0]
1274
- : `(${uniqueTypes.join(" | ")})`;
1275
- return { type: resultType, isStringLiteral: false };
1276
- }
1277
-
1278
- if (kind === "Scalar") {
1279
- const scalar = type as Scalar;
1280
- const format = getFormat(program, scalar);
1281
- const pattern = getPattern(program, scalar);
1282
-
1283
- if (format && formatToRust[format] && !pattern) {
1284
- return { type: formatToRust[format], isStringLiteral: false };
1285
- }
1286
- if (pattern) {
1287
- return { type: toPascalCase(scalar.name), isStringLiteral: false };
1288
- }
1289
- return {
1290
- type: scalarToRust[scalar.name] ?? scalar.name,
1291
- isStringLiteral: false,
1292
- };
1293
- }
1294
-
1295
- if (kind === "Intrinsic") {
1296
- const intrinsic = type as IntrinsicType;
1297
- const format = getFormat(program, type);
1298
- if (format && formatToRust[format]) {
1299
- return { type: formatToRust[format], isStringLiteral: false };
1300
- }
1301
- return {
1302
- type: scalarToRust[intrinsic.name] ?? "serde_json::Value",
1303
- isStringLiteral: false,
1304
- };
1305
- }
1306
-
1307
- if (kind === "String") {
1308
- return { type: "String", isStringLiteral: false };
1309
- }
1310
-
1311
- if (kind === "StringLiteral") {
1312
- return {
1313
- type: "String",
1314
- isStringLiteral: true,
1315
- stringLiteralValue: (type as StringLiteral).value,
1316
- };
1317
- }
1318
-
1319
- if (kind === "Boolean" || kind === "BooleanLiteral") {
1320
- return { type: "bool", isStringLiteral: false };
1321
- }
1322
-
1323
- if (kind === "Number" || kind === "NumericLiteral") {
1324
- return { type: "f64", isStringLiteral: false };
1325
- }
1326
-
1327
- return { type: "serde_json::Value", isStringLiteral: false };
1328
- }
1329
-
1330
- function toRustIdent(name: string): string {
1331
- const snakeCase = name.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
1332
- const result = snakeCase.replace(/[^a-z0-9_]/g, "_");
1333
- if (/^[0-9]/.test(result)) {
1334
- return "_" + result;
1335
- }
1336
- return result;
1337
- }
1338
-
1339
- function toPascalCase(name: string): string {
1340
- if (/^[^a-z]+$/.test(name)) {
1341
- return name;
1342
- }
1343
- if (/[-_]/.test(name)) {
1344
- return name
1345
- .split(/[-_]/)
1346
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
1347
- .join("");
1348
- }
1349
- return name.charAt(0).toUpperCase() + name.slice(1);
1350
- }
1351
-
1352
- function toRustVariantName(name: string): string {
1353
- return toPascalCase(name);
1354
- }
1355
-
1356
- function formatDoc(doc: string | undefined): string {
1357
- if (!doc) return "";
1358
- return doc
1359
- .split("\n")
1360
- .map((line) => `/// ${line.trim()}`)
1361
- .join("\n");
1362
- }
1363
-
1364
- function emitStringLiteralUnion(union: Union): string {
1365
- const parts: string[] = [];
1366
- const name = toPascalCase(union.name ?? "Value");
1367
- const variants = Array.from(union.variants.values());
1368
-
1369
- parts.push(
1370
- `#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]\n#[allow(clippy::enum_variant_names)]\npub enum ${name} {`,
1371
- );
1372
-
1373
- for (let i = 0; i < variants.length; i++) {
1374
- const literalType = variants[i].type as StringLiteral;
1375
- const variantName = toPascalCase(literalType.value);
1376
- const serdeValue = literalType.value;
1377
- if (i === 0) {
1378
- parts.push(` #[default]`);
1379
- }
1380
- parts.push(` #[serde(rename = "${serdeValue}")]`);
1381
- parts.push(` ${variantName},`);
1382
- }
1383
-
1384
- parts.push("}");
1385
- return parts.join("\n");
1386
- }
1387
-
1388
- function emitModel(
1389
- model: Model,
1390
- program: Program,
1391
- anonymousEnums: Map<string, AnonymousStringLiteralUnion>,
1392
- ): string {
1393
- const parts: string[] = [];
1394
- const name = toPascalCase(model.name);
1395
- const allProps = getAllProperties(model, program);
1396
-
1397
- const deriveAttrs = [
1398
- "Debug",
1399
- "Clone",
1400
- "serde::Serialize",
1401
- "serde::Deserialize",
1402
- ];
1403
-
1404
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1405
- const customDerives = (model as any)[rustDeriveKey] as
1406
- | RustDeriveInfo
1407
- | undefined;
1408
- if (customDerives) {
1409
- deriveAttrs.push(...customDerives.derives);
1410
- }
1411
-
1412
- parts.push(`#[derive(${deriveAttrs.join(", ")})]`);
1413
-
1414
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1415
- const customAttrs = (model as any)[rustAttrKey] as RustAttrInfo | undefined;
1416
- if (customAttrs) {
1417
- for (const attr of customAttrs.attrs) {
1418
- parts.push(`#[${attr}]`);
1419
- }
1420
- }
1421
-
1422
- if (allProps.size > 0) {
1423
- const fields: string[] = [];
1424
- for (const [propName, prop] of allProps) {
1425
- const doc = getDoc(program, prop);
1426
- const { type: rustType } = getRustTypeForProperty(
1427
- prop.type,
1428
- program,
1429
- anonymousEnums,
1430
- );
1431
- const optional = prop.optional ? true : false;
1432
- const fieldName = toRustIdent(propName);
1433
- const serdeRename =
1434
- propName !== fieldName ? `#[serde(rename = "${propName}")]` : "";
1435
-
1436
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1437
- const propAttrs = (prop as any)[rustAttrKey] as RustAttrInfo | undefined;
1438
-
1439
- if (doc) {
1440
- fields.push(` ${formatDoc(doc)}`);
1441
- }
1442
- if (propAttrs) {
1443
- for (const attr of propAttrs.attrs) {
1444
- fields.push(` #[${attr}]`);
1445
- }
1446
- }
1447
- if (serdeRename) {
1448
- fields.push(` ${serdeRename}`);
1449
- }
1450
- if (optional) {
1451
- fields.push(` #[serde(skip_serializing_if = "Option::is_none")]`);
1452
- }
1453
- fields.push(
1454
- ` pub ${fieldName}: ${optional ? `Option<${rustType}>` : rustType},`,
1455
- );
1456
- }
1457
- parts.push(`pub struct ${name} {
1458
- ${fields.join("\n")}
1459
- }`);
1460
- } else {
1461
- parts.push(`pub struct ${name}`);
1462
- parts.push("(());");
1463
- }
1464
-
1465
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1466
- const customImpl = (model as any)[rustImplKey] as RustImplInfo | undefined;
1467
- if (customImpl) {
1468
- parts.push(`
1469
- ${customImpl.impl}`);
1470
- }
1471
-
1472
- return parts.join("\n");
1473
- }
1474
-
1475
- function getAllProperties(
1476
- model: Model,
1477
- _program: Program,
1478
- ): Map<string, ModelProperty> {
1479
- const props = new Map<string, ModelProperty>();
1480
-
1481
- if (model.baseModel) {
1482
- const baseProps = getAllProperties(model.baseModel, _program);
1483
- for (const [key, value] of baseProps) {
1484
- props.set(key, value);
1485
- }
1486
- }
1487
-
1488
- for (const [key, value] of model.properties) {
1489
- props.set(key, value);
1490
- }
1491
-
1492
- return props;
1493
- }
1494
-
1495
- function emitEnum(enumType: Enum): string {
1496
- const parts: string[] = [];
1497
- const name = toPascalCase(enumType.name);
1498
- const members = Array.from(enumType.members.values());
1499
- const isString = members.every(
1500
- (m) => m.value === undefined || typeof m.value === "string",
1501
- );
1502
-
1503
- const baseDerives = [
1504
- "Debug",
1505
- "Clone",
1506
- "Copy",
1507
- "PartialEq",
1508
- "Eq",
1509
- "Hash",
1510
- "Default",
1511
- "serde::Serialize",
1512
- "serde::Deserialize",
1513
- ];
1514
-
1515
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1516
- const customDerives = (enumType as any)[rustDeriveKey] as
1517
- | RustDeriveInfo
1518
- | undefined;
1519
- const allDerives = [...baseDerives];
1520
- if (customDerives) {
1521
- allDerives.push(...customDerives.derives);
1522
- }
1523
-
1524
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1525
- const customAttrs = (enumType as any)[rustAttrKey] as
1526
- | RustAttrInfo
1527
- | undefined;
1528
- const attrLines: string[] = [];
1529
- if (customAttrs) {
1530
- for (const attr of customAttrs.attrs) {
1531
- attrLines.push(`#[${attr}]`);
1532
- }
1533
- }
1534
-
1535
- if (isString) {
1536
- parts.push(`#[derive(${allDerives.join(", ")})]`);
1537
- if (attrLines.length > 0) {
1538
- parts.push(...attrLines);
1539
- }
1540
- parts.push(`pub enum ${name} {`);
1541
- for (let i = 0; i < members.length; i++) {
1542
- const variantName = toRustVariantName(members[i].name);
1543
- const serdeValue = members[i].value ?? members[i].name;
1544
- if (i === 0) {
1545
- parts.push(` #[default]`);
1546
- }
1547
- parts.push(` #[serde(rename = "${serdeValue}")]`);
1548
- parts.push(` ${variantName},`);
1549
- }
1550
- } else {
1551
- parts.push(`#[derive(${allDerives.join(", ")})]`);
1552
- if (attrLines.length > 0) {
1553
- parts.push(...attrLines);
1554
- }
1555
- parts.push(`pub enum ${name} {`);
1556
- for (let i = 0; i < members.length; i++) {
1557
- const variantName = toRustVariantName(members[i].name);
1558
- const enumValue = members[i].value ?? 0;
1559
- if (i === 0) {
1560
- parts.push(` #[default]`);
1561
- }
1562
- parts.push(` ${variantName} = ${enumValue},`);
1563
- }
1564
- }
1565
- parts.push("}");
1566
- return parts.join("\n");
1567
- }
1568
-
1569
- function emitUnion(union: Union, program: Program): string {
1570
- const parts: string[] = [];
1571
- const name = toPascalCase(union.name ?? "Union");
1572
-
1573
- const variants = Array.from(union.variants.values());
1574
- if (variants.length === 0) {
1575
- parts.push(
1576
- `#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\npub enum ${name} {}\nimpl ${name} {\n pub fn new() -> Self { unreachable!() }\n}`,
1577
- );
1578
- return parts.join("\n");
1579
- }
1580
-
1581
- parts.push(
1582
- `#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n#[serde(untagged)]\npub enum ${name} {`,
1583
- );
1584
- for (let i = 0; i < variants.length; i++) {
1585
- const variant = variants[i];
1586
- const variantName = `Variant${i + 1}`;
1587
- const { type: rustType } = getRustTypeForProperty(
1588
- variant.type,
1589
- program,
1590
- new Map(),
1591
- );
1592
- parts.push(` ${variantName}(${rustType}),`);
1593
- }
1594
- parts.push("}");
1595
-
1596
- return parts.join("\n");
1597
- }
1598
-
1599
- function emitScalar(
1600
- scalar: Scalar,
1601
- program: Program,
1602
- ): { typeDef: string; impls: string[] } {
1603
- const format = getFormat(program, scalar);
1604
- const pattern = getPattern(program, scalar);
1605
- const structName = toPascalCase(scalar.name);
1606
- const impls: string[] = [];
1607
-
1608
- if (format && formatToRust[format]) {
1609
- return {
1610
- typeDef: `pub type ${structName} = ${formatToRust[format]};`,
1611
- impls: [],
1612
- };
1613
- }
1614
-
1615
- if (pattern) {
1616
- const rustType = scalarToRust[scalar.name] ?? "String";
1617
- impls.push(
1618
- `\nimpl TryFrom<String> for ${structName} {\n type Error = String;\n\n fn try_from(value: String) -> Result<Self, Self::Error> {\n let re = regex::Regex::new(r"${pattern}").unwrap();\n if re.is_match(&value) { Ok(Self(value)) } else { Err(format!("Invalid value: {}", value)) }\n }\n}`,
1619
- );
1620
-
1621
- return {
1622
- typeDef: `#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]\npub struct ${structName}(pub ${rustType});`,
1623
- impls,
1624
- };
1625
- }
1626
-
1627
- const rustType = scalarToRust[scalar.name] ?? "serde_json::Value";
1628
- return {
1629
- typeDef: `pub type ${structName} = ${rustType};`,
1630
- impls: [],
1631
- };
1632
- }
11
+ import {
12
+ RustEmitterOptions,
13
+ AnonymousStringLiteralUnion,
14
+ } from "./models/types.js";
15
+ import { isStdLibType, getAllOperations } from "./parser/index.js";
16
+ import {
17
+ emitModel,
18
+ emitEnum,
19
+ emitUnion,
20
+ emitScalar,
21
+ emitStringLiteralUnion,
22
+ } from "./generator/types_file.js";
23
+ import { generateServerTrait } from "./generator/server_trait.js";
24
+ import { generateResponseEnums } from "./generator/response_enums.js";
25
+ import { generateRouter } from "./generator/router.js";
1633
26
 
1634
27
  export async function $onEmit(
1635
28
  context: EmitContext<RustEmitterOptions>,
@@ -1707,7 +100,9 @@ export async function $onEmit(
1707
100
  );
1708
101
  for (let i = 0; i < anonEnum.variants.length; i++) {
1709
102
  const literal = anonEnum.variants[i];
1710
- const variantName = toPascalCase(literal.value);
103
+ const variantName = (
104
+ literal.value.charAt(0).toUpperCase() + literal.value.slice(1)
105
+ ).replace(/[^a-zA-Z0-9]/g, "");
1711
106
  if (i === 0) {
1712
107
  parts.push(` #[default]`);
1713
108
  }