-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayground.rs
More file actions
576 lines (533 loc) · 19.4 KB
/
Copy pathplayground.rs
File metadata and controls
576 lines (533 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use super::*;
use indoc::writedoc;
/// Generates playground-only service metadata from the same Rustdoc API input
/// used by the client generator. When `strip_examples` is true, suppresses
/// `exampleSource` (used by version snapshots to keep historical archives small).
pub fn generate_playground_services(
api: &ApiDefinition,
output_dir: &str,
target_version: u32,
strip_examples: bool,
) -> Result<()> {
let codegen_dir = Path::new(output_dir).join("codegen");
fs::create_dir_all(&codegen_dir)?;
validate_versioned_wrapper_shapes(api)?;
let code = generate_playground_services_code(api, target_version, strip_examples)?;
fs::write(codegen_dir.join("services.ts"), code)?;
Ok(())
}
fn generate_playground_services_code(
api: &ApiDefinition,
target_version: u32,
strip_examples: bool,
) -> Result<String> {
let wrappers = collect_versioned_wrappers(api);
let emit_versions = versioned_wrapper_emit_versions(api, &wrappers, target_version)?;
let aliases = selected_public_aliases(api, &wrappers, &emit_versions, target_version);
let ctx = CodecContext::default();
let services = public_services(api)?;
let explorer_type_ids = explorer_type_id_set(api, &aliases);
let mut out = String::new();
writedoc!(
out,
r#"
// Auto-generated by truapi-codegen. Do not edit.
import type {{ ServiceInfo }} from '../services-types.js';
export const services: ServiceInfo[] = [
"#
)
.unwrap();
for service in services {
let trait_def = service.trait_def;
let mut methods = included_methods(trait_def, &wrappers, target_version)?;
methods.sort_by_key(|method| (method_wire_sort_id(method), method.name.as_str()));
if methods.is_empty() {
continue;
}
writedoc!(
out,
"
{{
name: {name},
methods: [
",
name = ts_string_literal(&service_display_name(trait_def)),
)
.unwrap();
for method in methods {
let wire_version = method_wire_version(method, &wrappers, target_version)?;
let payload = emit_payload(&method.params, &wrappers, &ctx, wire_version)?;
let docs = split_playground_docs(method.docs.as_deref())?;
let method_type = match method.kind {
MethodKind::Request => "unary",
MethodKind::Subscription | MethodKind::ResultSubscription => "subscription",
};
let signature =
build_method_signature(method, &payload, &wrappers, &ctx, wire_version)?;
let doc_url = build_doc_url(trait_def, method);
writedoc!(
out,
"
{{
name: {name},
type: {ty},
signature: {signature},
docUrl: {doc_url},
",
name = ts_string_literal(&method.name),
ty = ts_string_literal(method_type),
signature = ts_string_literal(&signature),
doc_url = ts_string_literal(&doc_url),
)
.unwrap();
if let Some(description) = docs.description {
writeln!(
out,
" description: {},",
ts_string_literal(&description)
)
.unwrap();
}
let no_params = method.name == "host_handshake" || payload.param_list.is_empty();
if !no_params {
let request_description =
playground_request_description(api, &aliases, &payload.inner_type_ts);
writeln!(
out,
" requestDescription: {},",
ts_string_literal(&request_description)
)
.unwrap();
}
if let Some(client_example) = docs.client_example.as_deref()
&& !strip_examples
{
writeln!(
out,
" exampleSource: {},",
ts_string_literal(client_example)
)
.unwrap();
}
if let Some(id) = data_type_id_from_ts(&payload.inner_type_ts)
&& explorer_type_ids.contains(&id)
{
writeln!(out, " requestType: {},", ts_string_literal(&id)).unwrap();
}
let (response_inner, error_inner) =
method_response_inner_ts(method, &wrappers, &ctx, wire_version)?;
if let Some(id) = response_inner.as_deref().and_then(data_type_id_from_ts)
&& explorer_type_ids.contains(&id)
{
writeln!(out, " responseType: {},", ts_string_literal(&id)).unwrap();
}
if let Some(id) = error_inner.as_deref().and_then(data_type_id_from_ts)
&& explorer_type_ids.contains(&id)
{
writeln!(out, " errorType: {},", ts_string_literal(&id)).unwrap();
}
if let Some(perms) = &docs.permissions {
emit_permissions(&mut out, perms);
}
writeln!(out, " }},").unwrap();
}
writedoc!(
out,
"
],
}},
",
)
.unwrap();
}
writeln!(out, "];").unwrap();
Ok(out)
}
#[derive(Debug)]
pub(super) struct PlaygroundDocs {
pub(super) description: Option<String>,
pub(super) client_example: Option<String>,
pub(super) permissions: Option<MethodPermissions>,
}
/// Structured permission requirements extracted from a `# Permissions` doc section.
#[derive(Debug)]
pub(super) struct MethodPermissions {
pub(super) auth: Option<String>,
pub(super) prompt: Option<String>,
pub(super) permission_type: Option<String>,
pub(super) denial_error: Option<String>,
}
pub(super) fn split_playground_docs(docs: Option<&str>) -> Result<PlaygroundDocs> {
let Some(docs) = docs else {
return Ok(PlaygroundDocs {
description: None,
client_example: None,
permissions: None,
});
};
let mut description = Vec::new();
let mut client_example = Vec::new();
let mut permission_lines = Vec::new();
let mut in_client_example = false;
let mut in_permissions = false;
for line in docs.lines() {
let trimmed = line.trim();
if trimmed == "```ts" {
in_client_example = true;
in_permissions = false;
continue;
}
if in_client_example && trimmed == "```" {
in_client_example = false;
continue;
}
if in_client_example {
client_example.push(line);
continue;
}
if trimmed == "# Permissions" {
in_permissions = true;
continue;
}
if in_permissions && trimmed.starts_with("# ") {
in_permissions = false;
}
if in_permissions {
permission_lines.push(trimmed);
} else {
description.push(line);
}
}
let description = trim_doc_lines(&description);
let client_example = trim_doc_lines(&client_example);
let permissions = parse_permissions(&permission_lines);
Ok(PlaygroundDocs {
description,
client_example,
permissions,
})
}
/// Parses `- **key**: value` lines from a `# Permissions` section.
fn parse_permissions(lines: &[&str]) -> Option<MethodPermissions> {
let mut auth = None;
let mut prompt = None;
let mut permission_type = None;
let mut denial_error = None;
for line in lines {
let Some(rest) = line.strip_prefix("- **") else {
continue;
};
let Some((key, value)) = rest.split_once("**:") else {
continue;
};
let value = value.trim();
if value.is_empty() {
continue;
}
match key {
"auth" => auth = Some(value.to_string()),
"prompt" => prompt = Some(value.to_string()),
"permission" => permission_type = Some(value.to_string()),
"denial_error" => denial_error = Some(value.to_string()),
_ => {}
}
}
if auth.is_none() && prompt.is_none() && permission_type.is_none() && denial_error.is_none() {
return None;
}
Some(MethodPermissions {
auth,
prompt,
permission_type,
denial_error,
})
}
/// Fails if any public trait method lacks a valid ` ```ts ` example in its
/// doc comment. Every method renders an EXAMPLE tab in the playground from
/// the extracted `exampleSource`; a missing or mis-fenced example would
/// silently leave that tab empty and dump the snippet into the description.
pub(super) fn validate_method_examples(
api: &ApiDefinition,
wrappers: &HashMap<String, VersionedWrapper>,
target_version: u32,
) -> Result<()> {
for service in public_services(api)? {
let trait_def = service.trait_def;
for method in included_methods(trait_def, wrappers, target_version)? {
validate_example_docs(&trait_def.name, &method.name, method.docs.as_deref())?;
}
}
Ok(())
}
/// Checks a single method's doc comment carries exactly one ` ```ts ` example
/// that `split_playground_docs` can extract. Rejects a missing example, an
/// example fenced with an unrecognized label, and any code fence left behind
/// in the description (which means the example was not extracted).
fn validate_example_docs(trait_name: &str, method_name: &str, docs: Option<&str>) -> Result<()> {
let parsed = split_playground_docs(docs)?;
if let Some(description) = &parsed.description
&& description.contains("```")
{
bail!(
"{trait_name}::{method_name} has a code fence left in its description; \
examples must be fenced with ```ts so they are extracted into exampleSource"
);
}
if parsed.client_example.is_none() {
bail!(
"{trait_name}::{method_name} has no ```ts example in its doc comment; \
every TrUAPI method must carry one so the playground renders an EXAMPLE tab"
);
}
Ok(())
}
fn emit_permissions(out: &mut String, perms: &MethodPermissions) {
writeln!(out, " permissions: {{").unwrap();
if let Some(auth) = &perms.auth {
writeln!(out, " auth: {},", ts_string_literal(auth)).unwrap();
}
if let Some(prompt) = &perms.prompt {
writeln!(out, " prompt: {},", ts_string_literal(prompt)).unwrap();
}
if let Some(ptype) = &perms.permission_type {
writeln!(
out,
" permissionType: {},",
ts_string_literal(ptype)
)
.unwrap();
}
if let Some(denial) = &perms.denial_error {
writeln!(out, " denialError: {},", ts_string_literal(denial)).unwrap();
}
writeln!(out, " }},").unwrap();
}
pub(super) fn playground_type_name(value: &str) -> String {
value.replace("T.", "")
}
/// Returns the kebab-case explorer DataType id for a TS type expression
/// produced by `emit_payload`/`emit_response` (e.g. `T.HostAccountGetRequest`).
/// Returns `None` for `undefined`, primitives, arrays, generic instantiations,
/// or anything else that doesn't correspond to a single named DataType.
pub fn data_type_id_from_ts(value: &str) -> Option<String> {
let stripped = playground_type_name(value);
let trimmed = stripped.trim();
if trimmed.is_empty()
|| trimmed == "undefined"
|| trimmed == "void"
|| trimmed.contains(['[', '<', '|', '&', '(', '{', ' '])
{
return None;
}
if !trimmed
.chars()
.next()
.map(|c| c.is_ascii_uppercase())
.unwrap_or(false)
{
return None;
}
Some(name_to_kebab_id(trimmed))
}
/// Converts a TS type name (`HostAccountGetRequest`, `JsonRpcSubscription`)
/// to a kebab-case identifier (`host-account-get-request`,
/// `json-rpc-subscription`).
pub fn name_to_kebab_id(name: &str) -> String {
name.to_case(Case::Kebab)
}
/// Set of explorer DataType ids (kebab-case names) emitted by
/// [`crate::ts::generate_explorer`] for `api`. Used by the playground
/// emitter to gate `requestType`/`responseType`/`errorType` so they only
/// reference types the explorer actually surfaces.
pub fn explorer_type_id_set(
api: &ApiDefinition,
aliases: &BTreeMap<String, String>,
) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for ty in &api.types {
if detect_versioned_wrapper(ty).is_some() {
continue;
}
let public = aliases
.get(&ty.name)
.cloned()
.unwrap_or_else(|| ty.name.clone());
out.insert(name_to_kebab_id(&public));
}
out
}
/// Returns `(response_inner_ts, error_inner_ts)` for a method's return type,
/// stripping versioned wrappers. Either component is `None` when the return
/// shape has no corresponding inner type (e.g. a plain `Subscription` has no
/// error arm).
pub(super) fn method_response_inner_ts(
method: &MethodDef,
wrappers: &HashMap<String, VersionedWrapper>,
ctx: &CodecContext,
wire_version: Option<u32>,
) -> Result<(Option<String>, Option<String>)> {
match &method.return_type {
ReturnType::Result { ok, err } => {
let ok_resp = emit_response(ok, wrappers, ctx, wire_version)?;
let err_resp = emit_error_response(err, wrappers, ctx, wire_version)?;
Ok((Some(ok_resp.inner_type_ts), Some(err_resp.inner_type_ts)))
}
ReturnType::Subscription(item) => {
let resp = emit_response(item, wrappers, ctx, wire_version)?;
Ok((Some(resp.inner_type_ts), None))
}
ReturnType::ResultSubscription { item, err } => {
let resp = emit_response(item, wrappers, ctx, wire_version)?;
let err_resp = emit_error_response(err, wrappers, ctx, wire_version)?;
Ok((Some(resp.inner_type_ts), Some(err_resp.inner_type_ts)))
}
}
}
/// Rustdoc URL fragment for the trait method, relative to the cargo doc root
/// of the truapi crate (e.g. `api/account/trait.Account.html#method.get_account`).
/// `module_path` is the rustdoc path leading to the trait (e.g.
/// `["truapi", "api", "account"]`); the crate name is dropped because cargo doc
/// is published with the crate folder as the root.
fn build_doc_url(trait_def: &TraitDef, method: &MethodDef) -> String {
let module = trait_def
.module_path
.iter()
.skip(1)
.cloned()
.collect::<Vec<_>>()
.join("/");
format!(
"{module}/trait.{trait_name}.html#method.{method}",
trait_name = trait_def.name,
method = method.name,
)
}
fn build_method_signature(
method: &MethodDef,
payload: &PayloadEmission,
wrappers: &HashMap<String, VersionedWrapper>,
ctx: &CodecContext,
wire_version: Option<u32>,
) -> Result<String> {
let ts_method_name = to_camel_case(&strip_prefix(&method.name));
let arg = if payload.param_list.is_empty() {
String::new()
} else {
format!("request: {}", playground_type_name(&payload.inner_type_ts))
};
let return_ts = match &method.return_type {
ReturnType::Result { ok, err } => {
let ok_resp = emit_response(ok, wrappers, ctx, wire_version)?;
let err_resp = emit_error_response(err, wrappers, ctx, wire_version)?;
format!(
"Promise<Result<{}, {}>>",
playground_type_name(&ok_resp.inner_type_ts),
playground_type_name(&err_resp.inner_type_ts),
)
}
ReturnType::Subscription(item) => {
let response = emit_response(item, wrappers, ctx, wire_version)?;
format!(
"ObservableLike<{}>",
playground_type_name(&response.inner_type_ts),
)
}
ReturnType::ResultSubscription { item, err } => {
let response = emit_response(item, wrappers, ctx, wire_version)?;
let err_resp = emit_error_response(err, wrappers, ctx, wire_version)?;
format!(
"ObservableLike<{}, {}>",
playground_type_name(&response.inner_type_ts),
playground_type_name(&err_resp.inner_type_ts),
)
}
};
Ok(format!("{ts_method_name}({arg}): {return_ts}"))
}
fn playground_request_description(
api: &ApiDefinition,
aliases: &BTreeMap<String, String>,
value: &str,
) -> String {
let value = playground_type_name(value);
api.types
.iter()
.filter(|ty| {
aliases
.get(&ty.name)
.map(String::as_str)
.unwrap_or(&ty.name)
== value
})
.find_map(|ty| match &ty.kind {
TypeDefKind::Enum(variants) if is_unit_only_enum(ty) => {
Some(unit_enum_summary(variants))
}
_ => None,
})
.unwrap_or(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_to_kebab_id_handles_simple() {
assert_eq!(
name_to_kebab_id("HostAccountGetRequest"),
"host-account-get-request"
);
assert_eq!(
name_to_kebab_id("JsonRpcSubscription"),
"json-rpc-subscription"
);
}
#[test]
fn name_to_kebab_id_acronym_boundary() {
assert_eq!(name_to_kebab_id("URLPath"), "url-path");
assert_eq!(name_to_kebab_id("IOError"), "io-error");
}
#[test]
fn data_type_id_returns_none_for_non_named() {
assert_eq!(data_type_id_from_ts("undefined"), None);
assert_eq!(data_type_id_from_ts("void"), None);
assert_eq!(data_type_id_from_ts("T.Foo[]"), None);
assert_eq!(data_type_id_from_ts("string"), None);
assert_eq!(data_type_id_from_ts(""), None);
}
#[test]
fn validate_example_docs_accepts_ts_fence() {
let docs = "Summary line.\n\n```ts\nconst x = 1;\n```";
assert!(validate_example_docs("CoinPayment", "create_purse", Some(docs)).is_ok());
}
#[test]
fn validate_example_docs_rejects_missing_example() {
let docs = "Summary line with no example.";
let err = validate_example_docs("CoinPayment", "create_purse", Some(docs)).unwrap_err();
assert!(err.to_string().contains("no ```ts example"));
}
#[test]
fn validate_example_docs_rejects_missing_docs() {
let err = validate_example_docs("CoinPayment", "create_purse", None).unwrap_err();
assert!(err.to_string().contains("no ```ts example"));
}
#[test]
fn validate_example_docs_rejects_unrecognized_label() {
let docs = "Summary.\n\n```truapi-client-example\nconst x = 1;\n```";
let err = validate_example_docs("CoinPayment", "create_purse", Some(docs)).unwrap_err();
assert!(
err.to_string()
.contains("code fence left in its description")
);
}
#[test]
fn data_type_id_kebabs_named_types() {
assert_eq!(
data_type_id_from_ts("T.HostAccountGetRequest"),
Some("host-account-get-request".to_string())
);
assert_eq!(
data_type_id_from_ts("HostAccountGetResponse"),
Some("host-account-get-response".to_string())
);
}
}