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