-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathjava.test.ts
More file actions
727 lines (681 loc) · 32 KB
/
Copy pathjava.test.ts
File metadata and controls
727 lines (681 loc) · 32 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
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import type { JSONSchema7 } from "json-schema";
import {
collectNestedDiscriminatedUnionTypeNames,
generateRpcClass,
isMainModule,
renderEventVariantClass,
renderRpcTypes,
renderRpcWrappers,
schemaTypeToJava,
} from "./java.js";
import { RPC_VARIANT_OWNERS } from "./rpc-variant-owners.js";
test("preserves diagnostics configuration for session create and resume", async () => {
const files = await renderRpcTypes({
definitions: {
DiagnosticsConfiguration: {
type: "object",
properties: { sources: { $ref: "#/definitions/DiagnosticSourcesConfiguration" } },
required: ["sources"],
},
DiagnosticSourcesConfiguration: {
type: "object",
properties: { mcp: { type: "string" } },
},
},
}, {});
const configuration = [...files].find(([file]) => file.endsWith("/DiagnosticsConfiguration.java"));
assert.ok(configuration, "startup diagnostics must have a named generated configuration");
assert.match(configuration[1], /DiagnosticSourcesConfiguration sources/);
assert.ok([...files.keys()].some((file) => file.endsWith("/DiagnosticSourcesConfiguration.java")));
});
test("recognizes an entrypoint reached through a linked directory", (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "copilot-java-codegen-entrypoint-"));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const sourceDirectory = path.join(root, "source");
const linkedDirectory = path.join(root, "linked");
fs.mkdirSync(sourceDirectory);
fs.writeFileSync(path.join(sourceDirectory, "java.ts"), "");
fs.symlinkSync(sourceDirectory, linkedDirectory, process.platform === "win32" ? "junction" : "dir");
assert.equal(
isMainModule(
path.join(linkedDirectory, "java.ts"),
path.join(sourceDirectory, "java.ts"),
),
true,
);
});
function renderPayload(dataSchema: JSONSchema7): string {
return renderEventVariantClass({
typeName: "example.notification",
className: "ExampleNotificationEvent",
dataSchema,
}, "com.github.copilot.generated");
}
for (const keyword of ["anyOf", "oneOf"] as const) {
test(`root ${keyword} payload preserves raw JSON and existing data descriptors`, () => {
const source = renderPayload({
[keyword]: [
{ type: "object", properties: { kind: { const: "first" }, count: { type: "number" } } },
{ type: "object", properties: { kind: { const: "second" }, active: { type: "boolean" } } },
{ type: "null" },
],
});
assert.match(source, /public record ExampleNotificationEventData\(JsonNode raw\)/);
assert.match(source, /@JsonCreator\(mode = JsonCreator\.Mode\.DELEGATING\)\s+public ExampleNotificationEventData\s*\{/);
assert.match(source, /@JsonValue\s+public JsonNode raw\(\) \{ return raw; \}/);
assert.match(source, /public ExampleNotificationEventData\(\) \{\s+this\(JsonNodeFactory\.instance\.objectNode\(\)\);/);
assert.match(source, /public ExampleNotificationEventData getData\(\)/);
assert.match(source, /public void setData\(ExampleNotificationEventData data\)/);
});
test(`root ${keyword} with only one non-null alternative is not a raw union`, () => {
const source = renderPayload({
[keyword]: [
{ type: "object", properties: { message: { type: "string" } } },
{ type: "null" },
{ type: ["null"] },
{ const: null },
{ enum: [null] },
],
});
assert.doesNotMatch(source, /JsonNode|DELEGATING|JsonValue/);
});
}
test("ordinary and empty root objects retain their existing records", () => {
const source = renderPayload({
type: "object",
properties: { message: { type: "string" } },
});
assert.match(source, /@JsonProperty\("message"\) String message/);
assert.doesNotMatch(source, /JsonNode|DELEGATING|JsonValue/);
const empty = renderPayload({ type: "object", properties: {} });
assert.match(empty, /public record ExampleNotificationEventData\(\)/);
assert.doesNotMatch(empty, /JsonNode|DELEGATING|JsonValue/);
});
test("nested discriminated array items use their named Java type", () => {
const definitions: Record<string, JSONSchema7> = {
MessageResult: {
anyOf: [
{ $ref: "#/definitions/MessageDelivered" },
{ $ref: "#/definitions/MessageRejected" },
],
},
MessageDelivered: {
type: "object",
additionalProperties: false,
properties: {
status: { const: "delivered" },
actions: {
type: "array",
items: { $ref: "#/definitions/ActionChoice" },
},
},
},
MessageRejected: {
type: "object",
additionalProperties: false,
properties: {
status: { const: "rejected" },
reason: { type: "string" },
},
},
ActionChoice: {
anyOf: [
{ $ref: "#/definitions/PhoneAction" },
{ $ref: "#/definitions/EmailAction" },
],
},
PhoneAction: {
type: "object",
title: "PhoneAction",
additionalProperties: false,
properties: {
kind: { const: "phone" },
number: { type: "string" },
sources: {
type: "object",
additionalProperties: { $ref: "#/definitions/ActionSource" },
},
},
},
EmailAction: {
type: "object",
title: "EmailAction",
additionalProperties: false,
properties: {
kind: { const: "email" },
address: { type: "string" },
sources: {
type: "object",
additionalProperties: { $ref: "#/definitions/ActionSource" },
},
},
},
ActionSource: {
anyOf: [
{ $ref: "#/definitions/LocalActionSource" },
{ $ref: "#/definitions/RemoteActionSource" },
],
},
LocalActionSource: {
type: "object",
title: "LocalActionSource",
additionalProperties: false,
properties: {
location: { const: "local" },
},
},
RemoteActionSource: {
type: "object",
title: "RemoteActionSource",
additionalProperties: false,
properties: {
location: { const: "remote" },
url: { type: "string" },
},
},
};
const standaloneTypes = new Map<string, JSONSchema7>();
const promotedUnionTypes = collectNestedDiscriminatedUnionTypeNames(
{ $ref: "#/definitions/MessageResult" },
definitions
);
const result = schemaTypeToJava(
{
type: "array",
items: { $ref: "#/definitions/ActionChoice" },
},
false,
"MessageEnvelope",
"actions",
new Map(),
{
definitions,
standaloneTypes,
promotedUnionTypes,
}
);
assert.equal(result.javaType, "List<ActionChoice>");
assert.deepEqual([...standaloneTypes.keys()], ["ActionChoice"]);
assert.deepEqual([...promotedUnionTypes], ["ActionChoice", "ActionSource"]);
});
test("RPC records promote nested discriminated union references to sealed interfaces", async () => {
const definitions: Record<string, JSONSchema7> = {
InstallationConfirmationRequest: {
type: "object",
additionalProperties: false,
properties: {
review: { $ref: "#/definitions/InstallationReview" },
},
},
InstallationReview: {
anyOf: [
{
type: "object",
additionalProperties: false,
properties: {
resource: { type: "string", const: "mcp" },
review: { $ref: "#/definitions/McpInstallationReview" },
},
required: ["resource", "review"],
},
],
},
McpInstallationReview: {
anyOf: [
{
type: "object",
additionalProperties: false,
properties: {
action: { type: "string", const: "install" },
selectedChoice: { $ref: "#/definitions/McpPlanTransportChoice" },
},
required: ["action", "selectedChoice"],
},
{
type: "object",
additionalProperties: false,
properties: {
action: { type: "string", const: "uninstall" },
installationId: { type: "string" },
},
required: ["action", "installationId"],
},
],
},
McpInstallPlan: {
type: "object",
additionalProperties: false,
properties: {
transportChoices: {
type: "array",
items: { $ref: "#/definitions/McpPlanTransportChoice" },
},
},
},
McpPlanTransportChoice: {
anyOf: [
{ $ref: "#/definitions/McpPlanTransportChoicePackage" },
{ $ref: "#/definitions/McpPlanTransportChoiceRemote" },
],
},
McpPlanTransportChoicePackage: {
type: "object",
title: "McpPlanTransportChoicePackage",
additionalProperties: false,
properties: {
installMethod: { type: "string", const: "package" },
packageIdentifier: { type: "string" },
},
required: ["installMethod", "packageIdentifier"],
},
McpPlanTransportChoiceRemote: {
type: "object",
title: "McpPlanTransportChoiceRemote",
additionalProperties: false,
properties: {
installMethod: { type: "string", const: "remote" },
endpoint: { type: "string" },
},
required: ["installMethod", "endpoint"],
},
McpInstallationManagementResult: {
anyOf: [
{
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", const: "outcome" },
outcome: { $ref: "#/definitions/McpInstallationManagementOutcome" },
},
required: ["kind", "outcome"],
},
{
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", const: "invalid-request" },
message: { type: "string" },
},
required: ["kind", "message"],
},
],
},
McpInstallationManagementOutcome: {
anyOf: [
{
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", const: "operation" },
operation: { $ref: "#/definitions/McpInstallationOperationStatus" },
},
required: ["kind", "operation"],
},
{
type: "object",
additionalProperties: false,
properties: {
kind: { type: "string", const: "refused" },
reason: { type: "string" },
},
required: ["kind", "reason"],
},
],
},
McpInstallationOperationStatus: {
anyOf: [
{
type: "object",
additionalProperties: false,
properties: {
phase: { type: "string", const: "preparing" },
operationId: { type: "string" },
},
required: ["phase", "operationId"],
},
{
type: "object",
additionalProperties: false,
properties: {
phase: { type: "string", const: "completed" },
operationId: { type: "string" },
},
required: ["phase", "operationId"],
},
],
},
};
const files = await renderRpcTypes({
definitions,
clientGlobal: {
confirm: {
rpcMethod: "confirm",
params: { $ref: "#/definitions/InstallationConfirmationRequest" },
result: null,
},
plan: {
rpcMethod: "plan",
params: { $ref: "#/definitions/McpInstallPlan" },
result: null,
},
},
server: {
status: {
rpcMethod: "status",
params: null,
result: { $ref: "#/definitions/McpInstallationManagementResult" },
},
},
}, {});
assert.match(rpcSource(files, "InstallationConfirmationRequest"), /@JsonProperty\("review"\) McpInstallationReview review/);
assert.match(rpcSource(files, "McpInstallPlan"), /@JsonProperty\("transportChoices"\) List<McpPlanTransportChoice> transportChoices/);
assert.match(rpcSource(files, "McpInstallationManagementResultOutcome"), /private McpInstallationManagementOutcome outcome/);
assert.match(rpcSource(files, "McpInstallationManagementOutcomeOperation"), /@JsonProperty\("operation"\) McpInstallationOperationStatus operation/);
assert.match(rpcSource(files, "McpInstallationReview"), /public sealed interface McpInstallationReview permits McpInstallationReviewInstall, McpInstallationReviewUninstall/);
assert.match(rpcSource(files, "McpInstallationReview"), /JsonTypeInfo\.Id\.NAME, include = JsonTypeInfo\.As\.EXISTING_PROPERTY, property = "action", visible = true/);
assert.match(rpcSource(files, "McpInstallationReviewInstall"), /public record McpInstallationReviewInstall\(/);
assert.match(rpcSource(files, "McpInstallationReviewInstall"), /action = "install"/);
assert.match(rpcSource(files, "McpInstallationReviewInstall"), /import com\.fasterxml\.jackson\.annotation\.JsonTypeInfo;/);
assert.match(rpcSource(files, "McpInstallationReviewInstall"), /@JsonTypeInfo\(use = JsonTypeInfo\.Id\.NONE\)/);
assert.match(rpcSource(files, "McpPlanTransportChoice"), /property = "installMethod"/);
assert.match(rpcSource(files, "McpInstallationOperationStatus"), /property = "phase"/);
});
function sharedUnionFixture(roots: string[]) {
const definitions: Record<string, JSONSchema7> = {
SharedError: {
title: "SharedError",
type: "object",
additionalProperties: false,
properties: { kind: { const: "error" }, message: { type: "string" } },
},
};
const server: Record<string, unknown> = {};
for (const root of roots) {
definitions[root] = {
anyOf: [
{ $ref: "#/definitions/SharedError" },
{ type: "object", additionalProperties: false, properties: { kind: { const: "ok" } } },
],
};
server[root] = { rpcMethod: root, params: null, result: { $ref: `#/definitions/${root}` } };
}
return { definitions, server };
}
function rpcSource(files: Map<string, string>, name: string): string {
const source = files.get(`sdk/src/generated/java/com/github/copilot/generated/rpc/${name}.java`);
assert.ok(source, `missing ${name}.java`);
return source;
}
test("static OAuth config preserves the legacy four-argument constructor", () => {
const typeName = "McpOauthRequiredStaticClientConfig";
const source = generateRpcClass(typeName, {
type: "object",
additionalProperties: false,
properties: {
clientId: { type: "string" },
clientSecret: { type: ["string", "null"] },
publicClient: { type: ["boolean", "null"] },
grantType: { type: ["string", "null"] },
scope: { type: ["string", "null"] },
},
required: ["clientId"],
}, new Map(), "com.github.copilot.generated").code;
assert.match(
source,
/public McpOauthRequiredStaticClientConfig\(\s*String clientId,\s*String clientSecret,\s*Boolean publicClient,\s*String grantType\s*\) \{\s*this\(clientId, clientSecret, publicClient, grantType, null\);/s
);
});
for (const roots of [
["FirstResult", "HistoricalResult"],
["FirstResult", "HistoricalResult", "LastResult"],
]) {
test(`${roots.length} shared roots preserve historical ownership regardless of discovery order`, async () => {
const owners = { SharedError: "HistoricalResult" };
const fixture = sharedUnionFixture(roots);
const files = await renderRpcTypes(fixture, owners);
assert.match(rpcSource(files, "SharedError"), /class SharedError extends HistoricalResult/);
for (const root of roots.filter((name) => name !== "HistoricalResult")) {
assert.match(rpcSource(files, `${root}SharedError`), new RegExp(`class ${root}SharedError extends ${root}`));
assert.match(rpcSource(files, root), new RegExp(`value = ${root}SharedError.class, name = "error"`));
}
const reversed = sharedUnionFixture([...roots].reverse());
reversed.definitions = Object.fromEntries(Object.entries(reversed.definitions).reverse());
assert.deepEqual(
[...(await renderRpcTypes(reversed, owners))].sort(),
[...files].sort()
);
for (const root of roots) reversed.definitions[root].anyOf?.reverse();
const reordered = await renderRpcTypes(reversed, owners);
for (const [file, source] of files) {
const updated = reordered.get(file);
assert.ok(updated);
// Membership ordering is not API identity; retain the schema's
// annotation order without changing ownership or output names.
assert.deepEqual(updated.split("\n").map((line) => line.replace(/,$/, "")).sort(),
source.split("\n").map((line) => line.replace(/,$/, "")).sort());
}
});
}
test("RPC planning rejects unregistered shared ownership and missing historical owners", async () => {
const fixture = sharedUnionFixture(["FirstResult", "SecondResult"]);
await assert.rejects(renderRpcTypes(fixture, {}), /Ambiguous Java RPC owner for "SharedError"/);
await assert.rejects(renderRpcTypes(fixture, { SharedError: "MissingResult" }), /Missing historical Java RPC owner/);
await assert.rejects(renderRpcTypes(fixture, { RemovedVariant: "FirstResult" }), /Missing historical Java RPC owner/);
// A failed plan must not poison the next generation.
assert.ok((await renderRpcTypes(fixture, { SharedError: "FirstResult" })).size > 0);
});
test("RPC planning rejects incompatible shared schemas and contextual name collisions", async () => {
const incompatible = sharedUnionFixture(["FirstResult", "SecondResult"]);
incompatible.definitions.SecondResult.anyOf = [
{
...incompatible.definitions.SharedError,
properties: { kind: { const: "error" }, message: { type: "number" } },
},
{ type: "object", properties: { kind: { const: "ok" } } },
];
await assert.rejects(renderRpcTypes(incompatible, { SharedError: "FirstResult" }), /Incompatible schemas.*SharedError/);
const collision = sharedUnionFixture(["FirstResult", "SecondResult"]);
collision.definitions.FirstResult.anyOf?.push({
title: "SecondResultSharedError", type: "object", properties: { kind: { const: "extra" } },
});
await assert.rejects(renderRpcTypes(collision, { SharedError: "FirstResult" }), /Conflicting Java RPC contextual name/);
const rootCollision = sharedUnionFixture(["SharedError", "SecondResult"]);
// Avoid the fixture's self-reference: a concrete title collides with a root.
rootCollision.definitions.SharedError.anyOf = [
{ title: "SharedError", type: "object", properties: { kind: { const: "error" } } },
{ type: "object", properties: { kind: { const: "ok" } } },
];
delete rootCollision.server.SecondResult;
await assert.rejects(renderRpcTypes(rootCollision, {}), /Conflicting Java RPC variant name "SharedError"/);
});
test("nested standalone union memberships participate in the ownership plan", async () => {
const fixture = sharedUnionFixture(["FirstResult", "NestedResult"]);
delete fixture.server.NestedResult;
fixture.definitions.SharedError.properties!.detail = {
type: "array", items: { $ref: "#/definitions/NestedResult" },
};
const files = await renderRpcTypes(fixture, { SharedError: "FirstResult" });
assert.match(rpcSource(files, "NestedResultSharedError"), /extends NestedResult/);
assert.match(rpcSource(files, "SharedError"), /extends FirstResult/);
});
test("identical repeated root references emit each variant only once", async () => {
const fixture = sharedUnionFixture(["FirstResult"]);
const original = await renderRpcTypes(fixture, {});
fixture.server.alias = { rpcMethod: "alias", params: null, result: { $ref: "#/definitions/FirstResult" } };
assert.deepEqual([...(await renderRpcTypes(fixture, {}))].sort(), [...original].sort());
});
test("historical ABI registry retains the complete pre-intake ownership set", () => {
assert.equal(Object.keys(RPC_VARIANT_OWNERS).length, 61);
assert.equal(new Set(Object.values(RPC_VARIANT_OWNERS)).size, 12);
for (const name of ["CatalogNegotiationRefusedError", "CatalogInvalidRequestError", "CatalogUnavailableError"]) {
assert.equal(RPC_VARIANT_OWNERS[name], "CatalogSearchResult");
}
});
type LegacyScope = "server" | "session";
/** A request published with `contract`, `source` and `scope`, then extended with optional fields. */
function legacyRequestFixture(additions: 0 | 1 | 2, scope: LegacyScope = "server", legacy = ["contract", "source", "scope"]) {
const properties: Record<string, JSONSchema7> = {
...(scope === "session" ? { sessionId: { type: "string" } } : {}),
contract: { type: "string", description: "Caller contract." },
source: { type: "string" },
scope: { type: "string" },
};
if (additions >= 1) properties.policySessionId = { type: "string" };
if (additions >= 2) properties.traceId = { type: "string" };
const request: JSONSchema7 & Record<string, unknown> = {
type: "object",
properties,
required: [...(scope === "session" ? ["sessionId"] : []), "contract", "source"],
additionalProperties: false,
};
if (additions > 0) request["x-legacy-parameters"] = legacy;
const rpcMethod = `${scope === "session" ? "session." : ""}sample.plan`;
return {
[scope]: {
sample: {
plan: {
rpcMethod,
params: { $ref: "#/definitions/SamplePlanRequest" },
result: { type: "object", properties: { ok: { type: "boolean" } }, required: ["ok"] },
},
},
},
definitions: { SamplePlanRequest: request },
} as Parameters<typeof renderRpcTypes>[0];
}
function generatedFile(files: Map<string, string>, className: string): string | undefined {
return [...files].find(([file]) => file.endsWith(`/${className}.java`))?.[1];
}
async function renderLegacy(additions: 0 | 1 | 2, scope: LegacyScope = "server") {
const fixture = legacyRequestFixture(additions, scope);
const types = await renderRpcTypes(fixture, {});
const wrappers = await renderRpcWrappers(fixture);
const prefix = scope === "session" ? "Session" : "";
return {
params: generatedFile(types, `${prefix}SamplePlanParams`)!,
request: generatedFile(types, "SamplePlanRequest"),
api: generatedFile(wrappers, `${scope === "session" ? "Session" : "Server"}SampleApi`)!,
};
}
function publicConstructor(source: string): string | undefined {
return source.match(/public SamplePlanRequest\([^)]*\)/)?.[0];
}
test("x-legacy-parameters keeps the params record and adds a fluent request with a same-name overload", async () => {
const original = await renderLegacy(0);
assert.equal(original.request, undefined, "unmarked requests keep their existing generation");
assert.doesNotMatch(original.api, /SamplePlanRequest/);
const once = await renderLegacy(1);
assert.equal(once.params, original.params, "the params record keeps exactly its legacy components");
assert.ok(once.request);
assert.match(once.request, /public final class SamplePlanRequest \{/);
assert.equal(publicConstructor(once.request), "public SamplePlanRequest(String contract, String source)");
assert.match(once.request, /this\.contract = Objects\.requireNonNull\(contract, "contract"\);/);
assert.match(once.request, /public SamplePlanRequest setScope\(String value\)/);
assert.match(once.request, /public SamplePlanRequest setPolicySessionId\(String value\)/);
assert.match(once.request, /@JsonProperty\("policySessionId"\)\s+private String policySessionId;/);
assert.match(once.api, /public CompletableFuture<SamplePlanResult> plan\(SamplePlanParams params\) \{\s+return caller\.invoke\("sample\.plan", params,/);
assert.match(once.api, /public CompletableFuture<SamplePlanResult> plan\(SamplePlanRequest request\) \{\s+return caller\.invoke\("sample\.plan", Objects\.requireNonNull\(request, "request"\),/);
const twice = await renderLegacy(2);
assert.equal(twice.params, original.params, "a second optional addition leaves the record unchanged");
assert.equal(publicConstructor(twice.request!), publicConstructor(once.request));
assert.match(twice.request!, /public SamplePlanRequest setTraceId\(String value\)/);
const overloads = (api: string) => api.match(/public CompletableFuture<SamplePlanResult> plan\([^)]*\)/g);
assert.deepEqual(overloads(twice.api), overloads(once.api));
});
test("x-legacy-parameters session requests keep sessionId injected by the wrapper", async () => {
const original = await renderLegacy(0, "session");
const once = await renderLegacy(1, "session");
assert.equal(once.params, original.params);
assert.match(once.params, /@JsonProperty\("sessionId"\) String sessionId/);
assert.doesNotMatch(once.request!, /sessionId/);
assert.match(
once.api,
/plan\(SamplePlanRequest request\) \{\s+com\.fasterxml\.jackson\.databind\.node\.ObjectNode _p = MAPPER\.valueToTree\(Objects\.requireNonNull\(request, "request"\)\);\s+_p\.put\("sessionId", this\.sessionId\);\s+return caller\.invoke\("session\.sample\.plan", _p,/
);
});
test("x-legacy-parameters rejects metadata that would not preserve the original API", async () => {
await assert.rejects(
renderRpcTypes(legacyRequestFixture(1, "server", ["contract", "scope"]), {}),
/Invalid x-legacy-parameters for sample\.plan: required property source must be a legacy parameter/
);
await assert.rejects(
renderRpcTypes(legacyRequestFixture(1, "server", ["contract", "source", "missing"]), {}),
/unknown property missing/
);
await assert.rejects(
renderRpcTypes(legacyRequestFixture(1, "session", ["sessionId", "contract", "source"]), {}),
/implicit property sessionId cannot be a legacy parameter/
);
const client = legacyRequestFixture(1) as Record<string, unknown>;
client.clientSession = client.server;
delete client.server;
await assert.rejects(renderRpcTypes(client as Parameters<typeof renderRpcTypes>[0], {}), /only server and session requests are supported/);
});
/** A response record published with `name`, `status` and `error`, then extended with optional fields. */
function legacyRecordSchema(additions: string[], legacy: string[] | undefined = ["name", "status", "error"]): JSONSchema7 {
const properties: Record<string, JSONSchema7> = {
name: { type: "string", description: "Server name." },
status: { type: "string" },
};
for (const addition of additions.filter((name) => name === "owned")) properties[addition] = { type: "string" };
properties.error = { type: "string" };
for (const addition of additions.filter((name) => name !== "owned")) properties[addition] = { type: "string" };
const schema: JSONSchema7 & Record<string, unknown> = { type: "object", properties, required: ["name", "status"] };
if (additions.length > 0 && legacy) schema["x-legacy-parameters"] = legacy;
return schema;
}
function recordSource(schema: JSONSchema7): string {
return generateRpcClass("SampleServer", schema, new Map(), "com.github.copilot.generated.rpc").code;
}
function legacyConstructors(source: string): string[] {
return [...source.matchAll(/public SampleServer\(([^)]*)\) \{\s*this\(([^)]*)\);/g)].map(
(match) => `${match[1].replace(/\s+/g, " ").trim()} => ${match[2]}`
);
}
test("x-legacy-parameters response records keep every component and add the previous constructor", () => {
const original = recordSource(legacyRecordSchema([]));
assert.deepEqual(legacyConstructors(original), [], "unmarked records keep their existing generation");
const trailing = recordSource(legacyRecordSchema(["traceId"]));
assert.match(trailing, /record SampleServer\(\s*\/\*\* Server name\. \*\/\s*@JsonProperty\("name"\) String name,\s*@JsonProperty\("status"\) String status,\s*@JsonProperty\("error"\) String error,\s*@JsonProperty\("traceId"\) String traceId\s*\)/);
assert.deepEqual(legacyConstructors(trailing), ["String name, String status, String error => name, status, error, null"]);
const middle = recordSource(legacyRecordSchema(["owned"]));
assert.deepEqual(legacyConstructors(middle), ["String name, String status, String error => name, status, null, error"]);
const twice = recordSource(legacyRecordSchema(["owned", "traceId"]));
assert.deepEqual(legacyConstructors(twice), ["String name, String status, String error => name, status, null, error, null"]);
});
test("x-legacy-parameters response records reject metadata a positional constructor cannot preserve", () => {
assert.throws(
() => recordSource(legacyRecordSchema(["traceId"], ["status", "name", "error"])),
/Invalid x-legacy-parameters for SampleServer: legacy parameters must follow schema property order/
);
assert.throws(
() => recordSource(legacyRecordSchema(["traceId"], ["name", "error"])),
/required property status must be a legacy parameter/
);
});
test("x-legacy-parameters response records get the constructor through standalone generation", async () => {
const files = await renderRpcTypes({
server: {
sample: {
list: {
rpcMethod: "sample.list",
params: null,
result: {
type: "object",
properties: { servers: { type: "array", items: { $ref: "#/definitions/SampleServer" } } },
required: ["servers"],
},
},
},
},
definitions: { SampleServer: legacyRecordSchema(["owned"]) },
} as Parameters<typeof renderRpcTypes>[0], {});
assert.deepEqual(legacyConstructors(rpcSource(files, "SampleServer")), [
"String name, String status, String error => name, status, null, error",
]);
});