-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
Expand file tree
/
Copy pathBiDiGenerator.java
More file actions
1949 lines (1805 loc) · 86.3 KB
/
Copy pathBiDiGenerator.java
File metadata and controls
1949 lines (1805 loc) · 86.3 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.bidi;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.openqa.selenium.json.Json;
/**
* Generates Java BiDi module classes and their supporting POJOs from the flat binding-neutral
* {@code bidi_schema.json} produced by {@code project_bidi_schema.mjs}.
*
* <p>Usage: {@code BiDiGenerator <schema.json> <output.srcjar>}
*/
public class BiDiGenerator {
private static final String BASE_PKG = "org.openqa.selenium.bidi";
// Java reserved words that cannot appear as method names; append "_" to escape.
private static final Set<String> JAVA_RESERVED =
new java.util.HashSet<>(
java.util.Arrays.asList(
"abstract",
"assert",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extends",
"final",
"finally",
"float",
"for",
"goto",
"if",
"implements",
"import",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"strictfp",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"try",
"void",
"volatile",
"while"));
private static final String API_JAVADOC =
"/**\n"
+ " * This is an unsupported API. No compatibility guarantees are provided.\n"
+ " * It tracks the W3C WebDriver BiDi specification directly. As the specification\n"
+ " * evolves, this API will change or be removed without prior notice.\n"
+ " */\n";
private static final String LICENSE =
"// Licensed to the Software Freedom Conservancy (SFC) under one\n"
+ "// or more contributor license agreements. See the NOTICE file\n"
+ "// distributed with this work for additional information\n"
+ "// regarding copyright ownership. The SFC licenses this file\n"
+ "// to you under the Apache License, Version 2.0 (the\n"
+ "// \"License\"); you may not use this file except in compliance\n"
+ "// with the License. You may obtain a copy of the License at\n"
+ "//\n"
+ "// http://www.apache.org/licenses/LICENSE-2.0\n"
+ "//\n"
+ "// Unless required by applicable law or agreed to in writing,\n"
+ "// software distributed under the License is distributed on an\n"
+ "// \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n"
+ "// KIND, either express or implied. See the License for the\n"
+ "// specific language governing permissions and limitations\n"
+ "// under the License.\n\n"
+ "// This file is generated. Do not edit — regenerate via BiDiGenerator.\n\n";
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage: BiDiGenerator <schema.json> <output.srcjar>");
System.exit(1);
}
Path schemaFile = Paths.get(args[0]);
Path outputJar = Paths.get(args[1]).toAbsolutePath();
String schemaText = new String(Files.readAllBytes(schemaFile), UTF_8);
@SuppressWarnings("unchecked")
Map<String, Object> schema = (Map<String, Object>) new Json().toType(schemaText, Json.MAP_TYPE);
Path tempDir = Files.createTempDirectory("bidi-generated");
try {
new Generator(schema).generateAll(tempDir);
packToJar(tempDir, outputJar);
} finally {
deleteRecursive(tempDir);
}
}
// ═══════════════════════════════════════════════════════════════
// Generator
// ═══════════════════════════════════════════════════════════════
private static class Generator {
private final Map<String, Object> schema;
private final Map<String, Map<String, Object>> types = new LinkedHashMap<>();
/** Types reachable from command/event params and results — the only ones that get generated. */
private final Set<String> reachable;
/** Types reachable from command params — the only ones that need toMap(). */
private final Set<String> senderTypes;
/**
* Types reachable from command results or event params — i.e. types a caller can receive. A
* type in both this set and {@code senderTypes} is used bidirectionally (e.g.
* script.SharedReference: built to send as a script argument, and also received inside a remote
* value) and is the only case that needs an immutable value class plus a separate Builder — see
* {@link #appendBuilder}.
*/
private final Set<String> receivableTypes;
/**
* Maps a variant record/union name to every parent union it belongs to. A type can genuinely
* belong to more than one union at once (e.g. PrimitiveProtocolValue is a member of both
* RemoteValue and LocalValue) — unions are generated as interfaces specifically so this is a
* real "implements/extends more than one" relationship, not something that has to be dropped.
*/
private final Map<String, List<String>> variantParent;
/**
* Synthetic types (anonymous CDDL constructs hoisted by the normalizer) keyed by their owner
* type name. They are emitted as nested static classes instead of top-level files.
*/
private final Map<String, List<String>> syntheticChildren;
@SuppressWarnings("unchecked")
Generator(Map<String, Object> schema) {
this.schema = schema;
Map<String, Object> rawTypes = (Map<String, Object>) schema.get("types");
if (rawTypes != null) {
for (Map.Entry<String, Object> entry : rawTypes.entrySet()) {
types.put(entry.getKey(), (Map<String, Object>) entry.getValue());
}
}
List<Map<String, Object>> commands =
Optional.ofNullable((List<Map<String, Object>>) schema.get("commands"))
.orElse(Collections.emptyList());
List<Map<String, Object>> events =
Optional.ofNullable((List<Map<String, Object>>) schema.get("events"))
.orElse(Collections.emptyList());
this.reachable = computeReachable(commands, events);
this.senderTypes = computeSenderTypes();
this.receivableTypes = computeReceivableTypes();
this.variantParent = computeVariantParent();
this.syntheticChildren = computeSyntheticChildren();
}
@SuppressWarnings("unchecked")
private Map<String, List<String>> computeSyntheticChildren() {
Map<String, List<String>> result = new LinkedHashMap<>();
for (Map.Entry<String, Map<String, Object>> e : types.entrySet()) {
Map<String, Object> node = e.getValue();
if (!Boolean.TRUE.equals(node.get("synthetic"))) continue;
String owner = str(node, "owner");
if (owner != null) {
result.computeIfAbsent(owner, k -> new ArrayList<>()).add(e.getKey());
}
}
return result;
}
@SuppressWarnings("unchecked")
private Set<String> computeSenderTypes() {
List<Map<String, Object>> commands =
Optional.ofNullable((List<Map<String, Object>>) schema.get("commands"))
.orElse(Collections.emptyList());
Set<String> result = new LinkedHashSet<>();
java.util.ArrayDeque<String> queue = new java.util.ArrayDeque<>();
for (Map<String, Object> cmd : commands) {
seedRef(mapField(cmd, "params"), queue, result);
}
while (!queue.isEmpty()) {
String name = queue.poll();
Map<String, Object> node = types.get(name);
if (node == null) continue;
collectRefs(node, queue, result);
if (Boolean.TRUE.equals(node.get("synthetic"))) {
String owner = str(node, "owner");
if (owner != null && result.add(owner)) queue.add(owner);
}
// Union variants that extend a senderType union must also implement toMap().
// Include them so appendRecordBody generates the override.
if ("union".equals(str(node, "kind"))) {
List<String> variants = (List<String>) node.get("variants");
if (variants != null) {
for (String v : variants) {
if (result.add(v)) queue.add(v);
}
}
Map<String, Object> sel = mapField(node, "selector");
if (sel != null) {
List<Map<String, Object>> svs = (List<Map<String, Object>>) sel.get("variants");
if (svs != null) {
for (Map<String, Object> sv : svs) {
String ref = str(sv, "ref");
if (ref != null && result.add(ref)) queue.add(ref);
}
}
String def = str(sel, "default");
if (def != null && result.add(def)) queue.add(def);
}
}
}
return result;
}
@SuppressWarnings("unchecked")
private Set<String> computeReceivableTypes() {
List<Map<String, Object>> commands =
Optional.ofNullable((List<Map<String, Object>>) schema.get("commands"))
.orElse(Collections.emptyList());
List<Map<String, Object>> events =
Optional.ofNullable((List<Map<String, Object>>) schema.get("events"))
.orElse(Collections.emptyList());
Set<String> result = new LinkedHashSet<>();
java.util.ArrayDeque<String> queue = new java.util.ArrayDeque<>();
for (Map<String, Object> cmd : commands) {
seedRef(mapField(cmd, "result"), queue, result);
}
for (Map<String, Object> evt : events) {
seedRef(mapField(evt, "params"), queue, result);
}
while (!queue.isEmpty()) {
String name = queue.poll();
Map<String, Object> node = types.get(name);
if (node == null) continue;
collectRefs(node, queue, result);
if (Boolean.TRUE.equals(node.get("synthetic"))) {
String owner = str(node, "owner");
if (owner != null && result.add(owner)) queue.add(owner);
}
if ("union".equals(str(node, "kind"))) {
List<String> variants = (List<String>) node.get("variants");
if (variants != null) {
for (String v : variants) {
if (result.add(v)) queue.add(v);
}
}
Map<String, Object> sel = mapField(node, "selector");
if (sel != null) {
List<Map<String, Object>> svs = (List<Map<String, Object>>) sel.get("variants");
if (svs != null) {
for (Map<String, Object> sv : svs) {
String ref = str(sv, "ref");
if (ref != null && result.add(ref)) queue.add(ref);
}
}
String def = str(sel, "default");
if (def != null && result.add(def)) queue.add(def);
}
}
}
return result;
}
@SuppressWarnings("unchecked")
private Map<String, List<String>> computeVariantParent() {
Map<String, List<String>> result = new LinkedHashMap<>();
for (Map.Entry<String, Map<String, Object>> e : types.entrySet()) {
String unionName = e.getKey();
Map<String, Object> node = e.getValue();
if (!"union".equals(str(node, "kind"))) continue;
List<String> variants = (List<String>) node.get("variants");
if (variants == null) continue;
for (String variant : variants) {
result.computeIfAbsent(variant, k -> new ArrayList<>()).add(unionName);
}
}
return result;
}
/** Reachable parent unions for {@code typeName}, in declaration order. */
private List<String> reachableParents(String typeName) {
return variantParent.getOrDefault(typeName, Collections.emptyList()).stream()
.filter(reachable::contains)
.collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
void generateAll(Path outDir) throws IOException {
List<Map<String, Object>> commands =
Optional.ofNullable((List<Map<String, Object>>) schema.get("commands"))
.orElse(Collections.emptyList());
List<Map<String, Object>> events =
Optional.ofNullable((List<Map<String, Object>>) schema.get("events"))
.orElse(Collections.emptyList());
Map<String, List<Map<String, Object>>> cmdByDomain = groupByDomain(commands);
Map<String, List<Map<String, Object>>> evtByDomain = groupByDomain(events);
Set<String> domains = new LinkedHashSet<>();
domains.addAll(cmdByDomain.keySet());
domains.addAll(evtByDomain.keySet());
for (String domain : domains) {
generateModule(
domain,
cmdByDomain.getOrDefault(domain, Collections.emptyList()),
evtByDomain.getOrDefault(domain, Collections.emptyList()),
outDir);
}
for (Map.Entry<String, Map<String, Object>> entry : types.entrySet()) {
String name = entry.getKey();
if (!reachable.contains(name)) continue;
Map<String, Object> node = entry.getValue();
// Synthetic types are emitted as nested static classes inside their owner's file.
if (Boolean.TRUE.equals(node.get("synthetic"))) continue;
String kind = str(node, "kind");
if ("record".equals(kind)) {
generateRecord(name, node, outDir);
} else if ("enum".equals(kind)) {
generateEnum(name, node, outDir);
} else if ("union".equals(kind)) {
Map<String, Object> selector = mapField(node, "selector");
if (selector == null || !Boolean.TRUE.equals(selector.get("correlated"))) {
generateUnion(name, node, outDir);
}
// correlated unions are protocol-internal; skip code generation
}
// "alias" → resolved inline, no class generated
}
}
/** BFS over the type graph seeded by direct params/result refs from commands and events. */
@SuppressWarnings("unchecked")
private Set<String> computeReachable(
List<Map<String, Object>> commands, List<Map<String, Object>> events) {
Set<String> reachable = new LinkedHashSet<>();
java.util.ArrayDeque<String> queue = new java.util.ArrayDeque<>();
for (Map<String, Object> cmd : commands) {
seedRef(mapField(cmd, "params"), queue, reachable);
seedRef(mapField(cmd, "result"), queue, reachable);
}
for (Map<String, Object> evt : events) {
seedRef(mapField(evt, "params"), queue, reachable);
}
while (!queue.isEmpty()) {
String name = queue.poll();
Map<String, Object> node = types.get(name);
if (node == null) continue;
collectRefs(node, queue, reachable);
// Synthetic types are nested inside their owner — the owner must also be generated.
if (Boolean.TRUE.equals(node.get("synthetic"))) {
String owner = str(node, "owner");
if (owner != null && reachable.add(owner)) queue.add(owner);
}
// Union variant strings are not covered by collectRefs (which only follows {ref:...} maps).
// Add them explicitly so discriminated-dispatch targets are generated.
if ("union".equals(str(node, "kind"))) {
@SuppressWarnings("unchecked")
List<String> variants = (List<String>) node.get("variants");
if (variants != null) {
for (String v : variants) {
if (reachable.add(v)) queue.add(v);
}
}
@SuppressWarnings("unchecked")
Map<String, Object> sel = (Map<String, Object>) node.get("selector");
if (sel != null) {
@SuppressWarnings("unchecked")
List<Map<String, Object>> svs = (List<Map<String, Object>>) sel.get("variants");
if (svs != null) {
for (Map<String, Object> sv : svs) {
String ref = str(sv, "ref");
if (ref != null && reachable.add(ref)) queue.add(ref);
}
}
String def = str(sel, "default");
if (def != null && reachable.add(def)) queue.add(def);
}
}
}
return reachable;
}
// A command/event's params or result is not always a direct {"ref": ...} — it can be a
// container wrapping one, e.g. {"list": {"ref": "test.Item"}} for a command whose result is
// directly a list of records (see resolveCommandResultArg). Delegating to collectRefs, which
// already recurses through arbitrarily nested Map/List structures looking for "ref" keys,
// seeds those nested types too instead of only ever finding a ref at the very top level.
private static void seedRef(
Map<String, Object> typeRef, java.util.ArrayDeque<String> queue, Set<String> reachable) {
if (typeRef == null) return;
collectRefs(typeRef, queue, reachable);
}
@SuppressWarnings("unchecked")
private static void collectRefs(
Object node, java.util.ArrayDeque<String> queue, Set<String> reachable) {
if (node instanceof Map) {
Map<String, Object> m = (Map<String, Object>) node;
String ref = str(m, "ref");
if (ref != null && reachable.add(ref)) queue.add(ref);
for (Object v : m.values()) collectRefs(v, queue, reachable);
} else if (node instanceof List) {
for (Object item : (List<?>) node) collectRefs(item, queue, reachable);
}
}
// ─── Module class ─────────────────────────────────────────────
private void generateModule(
String domain,
List<Map<String, Object>> commands,
List<Map<String, Object>> events,
Path outDir)
throws IOException {
// Module classes live in bidi.protocol.module (not bidi.protocol.{domain}), deliberately
// kept separate from the hand-written bidi.module package so generated and hand-written
// facades never collide on package or class name during the migration.
String pkg = "org.openqa.selenium.bidi.protocol.module";
// Use "" as context domain so all POJO type refs in the module class are fully
// qualified (they live in bidi.{domain}, which never matches "").
String moduleDomain = "";
String cls = capitalize(domain);
StringBuilder sb = new StringBuilder();
sb.append(LICENSE);
sb.append("package ").append(pkg).append(";\n\n");
sb.append("import org.openqa.selenium.Beta;\n");
sb.append("import org.openqa.selenium.WebDriver;\n");
sb.append("import org.openqa.selenium.bidi.Command;\n");
sb.append("import org.openqa.selenium.bidi.ConverterFunctions;\n");
sb.append("import org.openqa.selenium.bidi.Event;\n");
sb.append("import org.openqa.selenium.bidi.Module;\n");
sb.append("\n");
sb.append(API_JAVADOC);
sb.append("@Beta\n");
sb.append("@SuppressWarnings(\"unchecked\")\n");
sb.append("public class ").append(cls).append(" extends Module {\n\n");
// Static Event constants
for (Map<String, Object> evt : events) {
String method = str(evt, "method");
String evtName = str(evt, "name");
Map<String, Object> paramsRef = mapField(evt, "params");
String evtConstant = toConstantName(evtName);
if (paramsRef != null) {
String javaType = resolveJavaType(paramsRef, moduleDomain, true);
String mapper = resolveEventMapper(paramsRef, moduleDomain);
sb.append(" public static final Event<")
.append(javaType)
.append("> ")
.append(evtConstant)
.append(" =\n")
.append(" new Event<>(\"")
.append(method)
.append("\", ")
.append(mapper)
.append(");\n\n");
} else {
sb.append(" public static final Event<Void> ")
.append(evtConstant)
.append(" =\n")
.append(" new Event<>(\"")
.append(method)
.append("\", map -> null);\n\n");
}
}
sb.append(" public ").append(cls).append("(WebDriver driver) {\n");
sb.append(" super(driver);\n");
sb.append(" }\n\n");
// Command methods
for (Map<String, Object> cmd : commands) {
String method = str(cmd, "method");
String cmdName = escapeReserved(str(cmd, "name"));
Map<String, Object> paramsRef = mapField(cmd, "params");
Map<String, Object> resultRef = mapField(cmd, "result");
String returnType;
String resultArg;
if (resultRef == null) {
returnType = "void";
resultArg = null;
} else {
returnType = resolveJavaType(resultRef, moduleDomain, true);
resultArg = resolveCommandResultArg(resultRef, moduleDomain);
}
String paramsArgDecl = "";
String paramsMapExpr = "java.util.Collections.emptyMap()";
if (paramsRef != null) {
String paramsType = resolveJavaType(paramsRef, moduleDomain, true);
paramsArgDecl = paramsType + " params";
paramsMapExpr = "params.toMap()";
}
sb.append(" public ")
.append(returnType)
.append(" ")
.append(cmdName)
.append("(")
.append(paramsArgDecl)
.append(") {\n");
if ("void".equals(returnType)) {
sb.append(" send(new Command<>(\"")
.append(method)
.append("\", ")
.append(paramsMapExpr)
.append("));\n");
} else if (resultArg != null) {
sb.append(" return send(new Command<>(\"")
.append(method)
.append("\", ")
.append(paramsMapExpr)
.append(", ")
.append(resultArg)
.append("));\n");
} else {
sb.append(" return send(new Command<>(\"")
.append(method)
.append("\", ")
.append(paramsMapExpr)
.append("));\n");
}
sb.append(" }\n\n");
}
sb.append("}\n");
writeFile(outDir, pkg.replace('.', '/') + "/" + cls + ".java", sb.toString());
}
// ─── Record POJO ──────────────────────────────────────────────
@SuppressWarnings("unchecked")
private void generateRecord(String typeName, Map<String, Object> node, Path outDir)
throws IOException {
String domain = domainOf(typeName);
String pkg = domainPackage(domain);
String cls = simpleNameOf(typeName);
boolean needsToMap = senderTypes.contains(typeName);
boolean isReceivable = receivableTypes.contains(typeName);
boolean extensible = Boolean.TRUE.equals(node.get("extensible"));
List<Map<String, Object>> rawFields =
(List<Map<String, Object>>)
Optional.ofNullable(node.get("fields")).orElse(Collections.emptyList());
boolean hasReservedWordField =
rawFields.stream().map(this::parseField).anyMatch(f -> !f.name.equals(f.wire));
// A receivable, non-extensible type deserializes through ConstructorCoercer (no generated
// fromJson of its own, unless a reserved-word field forces one — that bypasses
// ConstructorCoercer entirely via StaticInitializerCoercer, so the annotation would be
// inert there). Everywhere else, this opts the type into the "warn instead of silently
// ignoring" half of undeclared-field handling — extensible types don't need it, since they
// capture rather than drop.
boolean warnsOnUnknownFields = isReceivable && !extensible && !hasReservedWordField;
StringBuilder sb = new StringBuilder();
sb.append(LICENSE);
sb.append("package ").append(pkg).append(";\n\n");
// Collections/LinkedHashMap/Set are imported unconditionally rather than gated on
// needsToMap: a nested synthetic class in this same file may independently need them for
// toMap() or an extensible type's extras map (see appendRecordBody), and computing that
// file-wide isn't worth it against a harmless unused import.
sb.append("import java.util.Collections;\n");
sb.append("import java.util.LinkedHashMap;\n");
// Always imported: needed by fromJson() (see appendFromJson) whenever this class, or any
// nested synthetic class in this file, has an escaped-reserved-word field.
sb.append("import java.util.Map;\n");
sb.append("import java.util.Objects;\n");
sb.append("import java.util.Optional;\n");
sb.append("import java.util.Set;\n");
sb.append("import org.jspecify.annotations.Nullable;\n");
sb.append("import org.openqa.selenium.Beta;\n");
// BiDiException is needed by nested enum fromString() methods and union fromMap() methods.
sb.append("import org.openqa.selenium.bidi.BiDiException;\n");
sb.append("import org.openqa.selenium.json.Json;\n");
sb.append("import org.openqa.selenium.json.TypeToken;\n");
sb.append("import org.openqa.selenium.json.WarnOnUnknownFields;\n\n");
sb.append(API_JAVADOC);
sb.append("@Beta\n");
if (warnsOnUnknownFields) {
sb.append("@WarnOnUnknownFields\n");
}
// Unions are generated as interfaces, so a type belonging to more than one union (e.g.
// PrimitiveProtocolValue in both RemoteValue and LocalValue) genuinely implements all of
// them — no single-inheritance conflict to work around.
List<String> parentUnionRefs = reachableParents(typeName);
String implementsClause =
parentUnionRefs.isEmpty()
? ""
: " implements "
+ parentUnionRefs.stream()
.map(r -> resolveRefToJavaClass(r, domain))
.collect(Collectors.joining(", "));
sb.append("public class ").append(cls).append(implementsClause).append(" {\n\n");
appendRecordBody(sb, typeName, node, domain, " ");
appendNestedSynthetics(sb, typeName, domain, " ");
sb.append("}\n");
writeFile(outDir, pkg.replace('.', '/') + "/" + cls + ".java", sb.toString());
}
@SuppressWarnings("unchecked")
private void appendRecordBody(
StringBuilder sb, String typeName, Map<String, Object> node, String domain, String m) {
String cls =
Boolean.TRUE.equals(node.get("synthetic")) ? str(node, "label") : simpleNameOf(typeName);
List<Map<String, Object>> rawFields =
(List<Map<String, Object>>)
Optional.ofNullable(node.get("fields")).orElse(Collections.emptyList());
List<FieldInfo> fields =
rawFields.stream().map(this::parseField).collect(Collectors.toList());
List<FieldInfo> required =
fields.stream().filter(f -> f.required).collect(Collectors.toList());
List<FieldInfo> optional =
fields.stream().filter(f -> !f.required).collect(Collectors.toList());
boolean needsToMap = senderTypes.contains(typeName);
boolean isReceivable = receivableTypes.contains(typeName);
// An extra field may be sent only on an extensible type that is itself sendable, and an
// extensible, receivable type must preserve an undeclared field rather than drop it. The
// two are independent — a type can need either, both, or neither. Either one means a
// caller-built instance is not fully known up front, exactly like an optional field, so it
// folds into hasOptionals below and reuses the same sender-mutable / receiver-immutable /
// bidirectional-Builder split.
boolean extensible = Boolean.TRUE.equals(node.get("extensible"));
boolean needsExtrasSend = extensible && needsToMap;
boolean needsExtrasCapture = extensible && isReceivable;
boolean needsExtras = needsExtrasSend || needsExtrasCapture;
boolean hasOptionals = !optional.isEmpty() || needsExtras;
List<String> parentUnionRefs = reachableParents(typeName);
// A type reachable only from outbound command params (senderTypes) is caller-owned start
// to finish, so it keeps a single mutable class with fluent setters (the "else" branch
// below, unchanged from before). A type reachable only from inbound results/events is
// simplified the other way: since the caller never builds one, it gets no setters and no
// public constructor at all — only the deserializer's. A type reachable from *both* is the
// only case that must not expose mutation on a received instance: it becomes a fully
// immutable value class, with a separate nested Builder (see appendBuilder) as the only way
// to construct an outbound instance.
boolean immutable = hasOptionals && isReceivable;
boolean needsBuilder = immutable && needsToMap;
// Nullable optional fields need a <field>Set presence flag (see below); a type with a
// Builder needs a way for build() to state that flag explicitly rather than have it
// re-derived from Optional.isPresent() (which cannot tell "explicitly set to null" apart
// from "never set" — see appendConstructorAssignment).
List<FieldInfo> nullableOptional =
optional.stream().filter(f -> isNullable(f.typeRef)).collect(Collectors.toList());
// Fields — an immutable type's fields (including their xSet presence flags) are final:
// assigned once, in the single deserialization constructor, never mutated afterward.
for (FieldInfo f : fields) {
String jt = fieldJavaType(f, domain);
sb.append(m)
.append("private ")
.append(f.required || immutable ? "final " : "")
.append(jt)
.append(" ")
.append(f.name)
.append(";\n");
if (!f.required && isNullable(f.typeRef)) {
// Tracks whether the field was ever explicitly set, independent of the value —
// Optional<T> alone cannot distinguish "never set" from "explicitly set to null",
// and toMap() needs that distinction to send an explicit null on the wire. Only needed
// for fields the schema actually declares nullable; an optional field whose type is
// never null-able has no legal "explicit null" wire state to represent.
sb.append(m)
.append("private ")
.append(immutable ? "final " : "")
.append("boolean ")
.append(f.name)
.append("Set;\n");
}
}
// The "junk drawer" for a field the spec doesn't declare. Final and constructor-populated
// whenever the type is receivable — its only value on a deserialized instance comes off
// the wire; otherwise it is caller-populated directly via addExtension.
if (needsExtras) {
sb.append(m)
.append("private final Map<String, Object> extensions")
.append(needsExtrasCapture ? ";\n" : " = new LinkedHashMap<>();\n");
// Every field this type declares, by wire key — the line between "declared" (typed
// field) and "extra" (goes in the map above), used by both the outbound collision check
// (addExtension) and the inbound capture (fromJson).
sb.append(m).append("private static final Set<String> DEFINED_FIELDS =\n");
sb.append(m)
.append(" Set.of(")
.append(
fields.stream().map(f -> "\"" + f.wire + "\"").collect(Collectors.joining(", ")))
.append(");\n");
}
if (!fields.isEmpty() || needsExtras) sb.append("\n");
// User-facing constructor (required fields only) — sender-only types alone; an immutable
// type has no way to be constructed except its Builder (if it has one) or the deserializer.
if (hasOptionals && !immutable) {
sb.append(m).append("public ").append(cls).append("(");
sb.append(
required.stream().map(f -> paramDecl(f, domain)).collect(Collectors.joining(", ")));
sb.append(") {\n");
for (FieldInfo f : required) {
appendConstructorAssignment(sb, f, domain, m + " ");
}
for (FieldInfo f : optional) {
sb.append(m).append(" this.").append(f.name).append(" = Optional.empty();\n");
}
sb.append(m).append("}\n\n");
}
// Package-private constructor for ConstructorCoercer deserialization (not public API).
// When there is a user-facing constructor (any record with optional fields gets one, even
// if it ends up no-arg), this one is intentionally hidden. Skipped entirely when it would
// be a no-op duplicate of that public constructor: the public ctor's params are exactly
// `required`, and this one's are `required` (+ optional, + a needsBuilder SetOverride each,
// + extensions when needsExtrasCapture) — identical only when there are no real optional
// fields to add and no extras param either, which happens for a sender-only type whose only
// reason for hasOptionals is needsExtrasSend (not receivable, so no "extensions" ctor
// param), regardless of whether it has zero or several required fields.
boolean deserCtorDuplicatesPublic =
hasOptionals && !immutable && optional.isEmpty() && !needsExtrasCapture;
if (!deserCtorDuplicatesPublic) {
String deserCtorAccess = hasOptionals ? "" : "public ";
sb.append(m).append(deserCtorAccess).append(cls).append("(");
if (fields.isEmpty() && !needsExtrasCapture) {
sb.append(") {}\n\n");
} else {
List<String> ctorParams =
fields.stream()
.map(f -> paramDecl(f, domain))
.collect(Collectors.toCollection(ArrayList::new));
if (needsBuilder) {
for (FieldInfo f : nullableOptional) {
ctorParams.add("Optional<Boolean> " + f.name + "SetOverride");
}
}
if (needsExtrasCapture) {
ctorParams.add("Map<String, Object> extensions");
}
sb.append(String.join(", ", ctorParams));
sb.append(") {\n");
for (FieldInfo f : fields) {
appendConstructorAssignment(sb, f, domain, m + " ", needsBuilder);
}
if (needsExtrasCapture) {
// Copy rather than alias: when this constructor is called from a Builder's build(),
// the argument is the Builder's own live, mutable map — a later addExtension() call
// on a reused Builder must not be able to mutate an already-built instance out from
// under it (the BiDi low-level behavioral contract requires a built/received instance
// to stay immutable).
sb.append(m).append(" this.extensions = new LinkedHashMap<>(extensions);\n");
}
sb.append(m).append("}\n\n");
}
}
// Fluent setters for optional fields — sender-only types only. An immutable/receivable
// type never exposes these; use its Builder to construct one instead.
if (!immutable) {
for (FieldInfo f : optional) {
String baseType = resolveJavaType(f.typeRef, domain, true);
sb.append(m)
.append("public ")
.append(cls)
.append(" set")
.append(capitalize(f.name))
.append("(")
.append(baseType)
.append(" ")
.append(f.name)
.append(") {\n");
sb.append(m)
.append(" this.")
.append(f.name)
.append(" = Optional.ofNullable(")
.append(f.name)
.append(");\n");
if (isNullable(f.typeRef)) {
sb.append(m).append(" this.").append(f.name).append("Set = true;\n");
}
sb.append(m).append(" return this;\n");
sb.append(m).append("}\n\n");
}
if (needsExtrasSend) {
// An extra field may only be sent on an extensible type, and never one that shadows a
// declared field — that would leave two representations of one key.
sb.append(m)
.append("public ")
.append(cls)
.append(" addExtension(String key, Object value) {\n");
appendExtensionCollisionCheck(sb, m + " ");
sb.append(m).append(" this.extensions.put(key, value);\n");
sb.append(m).append(" return this;\n");
sb.append(m).append("}\n\n");
}
}
// Getters
for (FieldInfo f : fields) {
String jt = fieldJavaType(f, domain);
sb.append(m)
.append("public ")
.append(jt)
.append(" get")
.append(capitalize(f.name))
.append("() {\n");
sb.append(m).append(" return ").append(f.name).append(";\n");
sb.append(m).append("}\n\n");
}
if (needsExtras) {
sb.append(m).append("public Map<String, Object> getExtensions() {\n");
sb.append(m).append(" return Collections.unmodifiableMap(extensions);\n");
sb.append(m).append("}\n\n");
}
// toMap() only for types sent as command params
if (needsToMap) {
boolean overrides = parentUnionRefs.stream().anyMatch(senderTypes::contains);
if (overrides) sb.append(m).append("@Override\n");
sb.append(m).append("public Map<String, Object> toMap() {\n");
if (fields.isEmpty() && !needsExtrasSend) {
sb.append(m).append(" return Collections.emptyMap();\n");
} else {
sb.append(m).append(" Map<String, Object> map = new LinkedHashMap<>();\n");
for (FieldInfo f : required) {
String serExpr = serializeExpr(f.name, f.typeRef, domain);
sb.append(m)
.append(" map.put(\"")
.append(f.wire)
.append("\", ")
.append(serExpr)
.append(");\n");
}
for (FieldInfo f : optional) {
if (isNullable(f.typeRef)) {
// A field that was never set is omitted from the wire entirely; a field that was
// explicitly set to null must serialize as an explicit null rather than also being
// omitted, so presence (xSet) and value-nullability are checked separately. Only
// fields the schema declares nullable get this treatment — an optional field whose
// type is never null-able has no legal null wire state.
String serExpr = serializeExpr(f.name + ".get()", f.typeRef, domain);
sb.append(m).append(" if (").append(f.name).append("Set) {\n");
sb.append(m)
.append(" map.put(\"")
.append(f.wire)
.append("\", ")
.append(f.name)
.append(".isPresent() ? ")
.append(serExpr)
.append(" : null);\n");
sb.append(m).append(" }\n");
} else {
String serExpr = serializeExpr("v", f.typeRef, domain);
sb.append(m)
.append(" ")
.append(f.name)
.append(".ifPresent(v -> map.put(\"")
.append(f.wire)
.append("\", ")
.append(serExpr)
.append("));\n");
}
}
if (needsExtrasSend) {
sb.append(m).append(" extensions.forEach(map::put);\n");
}
sb.append(m).append(" return Collections.unmodifiableMap(map);\n");
}
sb.append(m).append("}\n\n");
}
if (needsBuilder) {
appendBuilder(sb, cls, fields, required, optional, domain, m, needsExtras);
}
// A field whose spec name collides with a Java reserved word (e.g.
// script.CallFunctionParameters'
// "this", session.UserPromptHandler's "default") gets its Java identifier escaped
// (escapeReserved) but keeps its original wire key. ConstructorCoercer matches JSON
// properties to constructor parameters by exact name, so it can never find the wire key
// "this" for a parameter named "this_" — that field would silently deserialize as absent.
// fromJson reads every field by its wire key directly and calls the all-fields constructor,
// bypassing that name-matching entirely; StaticInitializerCoercer picks up a class's own
// "fromJson" ahead of ConstructorCoercer whenever one is present. A type that must preserve
// undeclared fields on receipt needs the same bypass for the same reason: ConstructorCoercer
// has no notion of "collect whatever's left over."
boolean needsFromJson =
fields.stream().anyMatch(f -> !f.name.equals(f.wire)) || needsExtrasCapture;
if (needsFromJson) {
appendFromJson(
sb, cls, fields, domain, m, needsBuilder, nullableOptional, needsExtrasCapture);
}
}
// A caller-added extension must never shadow a declared field's wire key — that would leave
// two representations of the same key with no defined precedence.
private void appendExtensionCollisionCheck(StringBuilder sb, String bodyIndent) {
sb.append(bodyIndent).append("if (DEFINED_FIELDS.contains(key)) {\n");
sb.append(bodyIndent)
.append(
" throw new BiDiException(\"Cannot add an extension for a declared field: \" +"
+ " key);\n");
sb.append(bodyIndent).append("}\n");
}
private void appendFromJson(
StringBuilder sb,
String cls,
List<FieldInfo> fields,
String domain,
String m,
boolean needsBuilder,
List<FieldInfo> nullableOptional,
boolean needsExtrasCapture) {
sb.append("\n")
.append(m)
.append("private static ")
.append(cls)
.append(" fromJson(Map<String, Object> map) {\n");
sb.append(m).append(" Json json = new Json();\n");
for (FieldInfo f : fields) {
String decodeType =
f.required ? resolveJavaType(f.typeRef, domain, true) : fieldJavaType(f, domain);