@kizunajs/kotlin 2.0.0-beta.4 → 2.0.0-beta.40
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.
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{generator-CVPHq7oN.mjs → generator-Dm08BYru.mjs} +526 -109
- package/dist/{generator-DgTjvOZ-.cjs → generator-DyQN5KLn.cjs} +530 -107
- package/dist/index.cjs +39 -8
- package/dist/index.d.cts +26 -38
- package/dist/index.d.mts +26 -38
- package/dist/index.mjs +38 -9
- package/package.json +8 -8
|
@@ -56,6 +56,7 @@ var TypeRegistry = class {
|
|
|
56
56
|
explicitIds = /* @__PURE__ */ new Set();
|
|
57
57
|
sealedVariantPayloads = /* @__PURE__ */ new Set();
|
|
58
58
|
sealedVariantPaths = /* @__PURE__ */ new Map();
|
|
59
|
+
brands = /* @__PURE__ */ new Map();
|
|
59
60
|
usesJsonElement = false;
|
|
60
61
|
constructor(camelCaseProperties = false, unknownEnumCase = false) {
|
|
61
62
|
this.camelCaseProperties = camelCaseProperties;
|
|
@@ -99,6 +100,15 @@ var TypeRegistry = class {
|
|
|
99
100
|
sealedVariantPath(name) {
|
|
100
101
|
return this.sealedVariantPaths.get(name);
|
|
101
102
|
}
|
|
103
|
+
addBrand(brand) {
|
|
104
|
+
const existing = this.brands.get(brand.name);
|
|
105
|
+
if (existing !== void 0 && existing.rawType !== brand.rawType) throw new Error(`@kizunajs/kotlin: brand ${stringify(brand.name)} wraps both ${existing.rawType} and ${brand.rawType}. Give each its own name.`);
|
|
106
|
+
if (this.types.has(brand.name)) throw new Error(`@kizunajs/kotlin: brand ${stringify(brand.name)} has the same name as a model. Give each its own name.`);
|
|
107
|
+
this.brands.set(brand.name, brand);
|
|
108
|
+
}
|
|
109
|
+
allBrands() {
|
|
110
|
+
return Array.from(this.brands.values());
|
|
111
|
+
}
|
|
102
112
|
warnJsonElement(hint, reason) {
|
|
103
113
|
this.usesJsonElement = true;
|
|
104
114
|
this.warningSet.add(`${hint}: ${reason}`);
|
|
@@ -132,6 +142,7 @@ const objectFields = (schema, registry, hint, shape = (0, kizunajs_generator.rea
|
|
|
132
142
|
wireName: key,
|
|
133
143
|
type: result.expression,
|
|
134
144
|
optional: result.optional,
|
|
145
|
+
requiredNullable: result.requiredNullable,
|
|
135
146
|
description: (0, kizunajs_generator.readMetaDescription)(value),
|
|
136
147
|
isFile: result.isFile,
|
|
137
148
|
deprecated: deprecation !== void 0,
|
|
@@ -141,7 +152,29 @@ const objectFields = (schema, registry, hint, shape = (0, kizunajs_generator.rea
|
|
|
141
152
|
return fields;
|
|
142
153
|
};
|
|
143
154
|
const stringify = (value) => JSON.stringify(value);
|
|
155
|
+
const BRANDABLE_TYPES = new Set([
|
|
156
|
+
"String",
|
|
157
|
+
"Int",
|
|
158
|
+
"Long",
|
|
159
|
+
"Double",
|
|
160
|
+
"Boolean",
|
|
161
|
+
"Instant"
|
|
162
|
+
]);
|
|
144
163
|
const mapType = (schema, registry, hint) => {
|
|
164
|
+
const result = mapUnbrandedType(schema, registry, hint);
|
|
165
|
+
const brand = (0, kizunajs_generator.readMetaBrand)(schema);
|
|
166
|
+
if (brand === void 0 || !BRANDABLE_TYPES.has(result.expression)) return result;
|
|
167
|
+
const name = (0, kizunajs_generator.sanitizeIdentifier)(brand);
|
|
168
|
+
registry.addBrand({
|
|
169
|
+
name,
|
|
170
|
+
rawType: result.expression
|
|
171
|
+
});
|
|
172
|
+
return {
|
|
173
|
+
expression: name,
|
|
174
|
+
optional: false
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
const mapUnbrandedType = (schema, registry, hint) => {
|
|
145
178
|
if ((0, kizunajs_generator.isFileSchema)(schema)) return {
|
|
146
179
|
expression: "MultipartFile",
|
|
147
180
|
optional: false,
|
|
@@ -151,6 +184,8 @@ const mapType = (schema, registry, hint) => {
|
|
|
151
184
|
expression: "ByteArray",
|
|
152
185
|
optional: false
|
|
153
186
|
};
|
|
187
|
+
const model = (0, kizunajs_generator.readModelSchema)(schema);
|
|
188
|
+
if (model !== void 0 && model !== schema) return mapUnbrandedType(model, registry, hint);
|
|
154
189
|
const id = (0, kizunajs_generator.readMetaId)(schema);
|
|
155
190
|
const def = (0, kizunajs_generator.readDef)(schema);
|
|
156
191
|
const discriminated = (0, kizunajs_generator.readDiscriminatedUnion)(schema);
|
|
@@ -163,6 +198,7 @@ const mapType = (schema, registry, hint) => {
|
|
|
163
198
|
name: enumName,
|
|
164
199
|
discriminator: discriminated.discriminator,
|
|
165
200
|
variants: [],
|
|
201
|
+
unknownCase: registry.unknownEnumCase || (0, kizunajs_generator.readMetaExtensible)(schema),
|
|
166
202
|
description: (0, kizunajs_generator.readMetaDescription)(schema)
|
|
167
203
|
});
|
|
168
204
|
const variants = [];
|
|
@@ -196,6 +232,7 @@ const mapType = (schema, registry, hint) => {
|
|
|
196
232
|
name: enumName,
|
|
197
233
|
discriminator: discriminated.discriminator,
|
|
198
234
|
variants,
|
|
235
|
+
unknownCase: registry.unknownEnumCase || (0, kizunajs_generator.readMetaExtensible)(schema),
|
|
199
236
|
description: (0, kizunajs_generator.readMetaDescription)(schema)
|
|
200
237
|
});
|
|
201
238
|
}
|
|
@@ -232,6 +269,7 @@ const mapType = (schema, registry, hint) => {
|
|
|
232
269
|
return {
|
|
233
270
|
expression: innerResult.expression.endsWith("?") ? innerResult.expression : `${innerResult.expression}?`,
|
|
234
271
|
optional: true,
|
|
272
|
+
requiredNullable: nullable && !optional,
|
|
235
273
|
isFile: innerResult.isFile
|
|
236
274
|
};
|
|
237
275
|
}
|
|
@@ -318,7 +356,7 @@ const mapType = (schema, registry, hint) => {
|
|
|
318
356
|
name: enumName,
|
|
319
357
|
cases,
|
|
320
358
|
description: (0, kizunajs_generator.readMetaDescription)(schema),
|
|
321
|
-
unknownCase: registry.unknownEnumCase
|
|
359
|
+
unknownCase: registry.unknownEnumCase || (0, kizunajs_generator.readMetaExtensible)(schema)
|
|
322
360
|
});
|
|
323
361
|
return {
|
|
324
362
|
expression: enumName,
|
|
@@ -416,6 +454,7 @@ const sanitizeCaseName = (literal) => {
|
|
|
416
454
|
const collectObjectFields = (schema, registry, hint) => {
|
|
417
455
|
return objectFields(schema, registry, hint);
|
|
418
456
|
};
|
|
457
|
+
const hasDefault = (field) => field.optional && field.requiredNullable !== true;
|
|
419
458
|
const objectFieldCount = (schema) => {
|
|
420
459
|
return Object.keys((0, kizunajs_generator.readObjectShape)(schema) ?? {}).length;
|
|
421
460
|
};
|
|
@@ -440,7 +479,11 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
|
|
|
440
479
|
const baseHint = (0, kizunajs_generator.toPascalCase)(fullJoinedName);
|
|
441
480
|
const pathParams = (0, kizunajs_generator.parsePath)(route.path).paramNames;
|
|
442
481
|
const declaredPathParams = route.pathParams ? collectObjectFields(route.pathParams, registry, `${baseHint}Params`) : [];
|
|
443
|
-
const
|
|
482
|
+
const queryShape = route.query ? (0, kizunajs_generator.readObjectShape)(route.query) ?? {} : {};
|
|
483
|
+
const queryFields = route.query ? collectObjectFields(route.query, registry, `${baseHint}Query`).map((field) => ({
|
|
484
|
+
...field,
|
|
485
|
+
json: (0, kizunajs_generator.isJsonQueryField)(queryShape[field.wireName])
|
|
486
|
+
})) : [];
|
|
444
487
|
const headerFields = route.headers ? collectObjectFields(route.headers, registry, `${baseHint}Headers`) : [];
|
|
445
488
|
const bodyDefType = route.body?._def?.type ?? route.body?.def?.type;
|
|
446
489
|
let bodyDescriptor;
|
|
@@ -497,11 +540,16 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
|
|
|
497
540
|
if (mode === "events" && (0, kizunajs_generator.isNamedStream)(responseValue.stream)) stream = {
|
|
498
541
|
status,
|
|
499
542
|
mode,
|
|
500
|
-
events: Object.entries(responseValue.stream).map(([name, schema]) =>
|
|
501
|
-
name
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
543
|
+
events: Object.entries(responseValue.stream).map(([name, schema]) => {
|
|
544
|
+
const type = mapType(schema, registry, `${baseHint}${(0, kizunajs_generator.toPascalCase)(name)}`).expression;
|
|
545
|
+
const found = registry.get(type);
|
|
546
|
+
return {
|
|
547
|
+
name,
|
|
548
|
+
caseName: (0, kizunajs_generator.toPascalCase)(name),
|
|
549
|
+
type,
|
|
550
|
+
unknownCase: found?.kind === "sealed-class" && found.unknownCase
|
|
551
|
+
};
|
|
552
|
+
})
|
|
505
553
|
};
|
|
506
554
|
else if (mode === "events") stream = {
|
|
507
555
|
status,
|
|
@@ -516,18 +564,23 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
|
|
|
516
564
|
successResponses.push({
|
|
517
565
|
status,
|
|
518
566
|
type: stream.messageType ?? "Event",
|
|
519
|
-
responseHeaders: headersSchema ? collectObjectFields(headersSchema, registry, `${baseHint}ResponseHeaders`) : []
|
|
567
|
+
responseHeaders: headersSchema ? collectObjectFields(headersSchema, registry, `${baseHint}ResponseHeaders`) : [],
|
|
568
|
+
isText: false
|
|
520
569
|
});
|
|
521
570
|
continue;
|
|
522
571
|
}
|
|
523
|
-
const
|
|
572
|
+
const bodySchema = (0, kizunajs_generator.resolveResponseBody)(responseValue);
|
|
573
|
+
const responseContentType = (0, kizunajs_generator.resolveResponseContentType)(responseValue);
|
|
574
|
+
const isText = !(0, kizunajs_generator.isBinarySchema)(bodySchema) && responseContentType !== void 0 && !(0, kizunajs_generator.isJsonMediaType)(responseContentType);
|
|
575
|
+
const typeExpression = mapType(bodySchema, registry, responseHint).expression;
|
|
524
576
|
if ((0, kizunajs_generator.isSuccessStatus)(status)) {
|
|
525
577
|
const headersSchema = (0, kizunajs_generator.resolveResponseHeaders)(responseValue);
|
|
526
578
|
const perStatusHeaderFields = headersSchema ? collectObjectFields(headersSchema, registry, `${baseHint}ResponseHeaders`) : [];
|
|
527
579
|
successResponses.push({
|
|
528
580
|
status,
|
|
529
581
|
type: typeExpression,
|
|
530
|
-
responseHeaders: perStatusHeaderFields
|
|
582
|
+
responseHeaders: perStatusHeaderFields,
|
|
583
|
+
isText
|
|
531
584
|
});
|
|
532
585
|
} else errorCases.push({
|
|
533
586
|
caseName: (0, kizunajs_generator.statusToCamelCase)(status),
|
|
@@ -535,7 +588,7 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
|
|
|
535
588
|
type: typeExpression
|
|
536
589
|
});
|
|
537
590
|
}
|
|
538
|
-
if (
|
|
591
|
+
if ((0, kizunajs_generator.validatesRequest)(route)) {
|
|
539
592
|
const has400 = errorCases.some((candidate) => candidate.status === 400);
|
|
540
593
|
errorCases.push({
|
|
541
594
|
caseName: has400 ? "validationError" : (0, kizunajs_generator.statusToCamelCase)(400),
|
|
@@ -580,7 +633,7 @@ const buildRouteMethod = (routeKey, route, registry, deprecated, deprecationMess
|
|
|
580
633
|
stream
|
|
581
634
|
};
|
|
582
635
|
};
|
|
583
|
-
const
|
|
636
|
+
const kotlinRoutesWalk = (options) => {
|
|
584
637
|
const flatMethods = [];
|
|
585
638
|
const groupMap = /* @__PURE__ */ new Map();
|
|
586
639
|
return {
|
|
@@ -612,7 +665,7 @@ const kotlinGenerator = (0, kizunajs_generator.createGenerator)((options, _api)
|
|
|
612
665
|
};
|
|
613
666
|
}
|
|
614
667
|
};
|
|
615
|
-
}
|
|
668
|
+
};
|
|
616
669
|
const KOTLIN_KEYWORDS = new Set([
|
|
617
670
|
"as",
|
|
618
671
|
"break",
|
|
@@ -646,6 +699,10 @@ const KOTLIN_KEYWORDS = new Set([
|
|
|
646
699
|
const escapeKeyword = (name) => {
|
|
647
700
|
return KOTLIN_KEYWORDS.has(name) ? `\`${name}\`` : name;
|
|
648
701
|
};
|
|
702
|
+
const defaultArgument = (field) => {
|
|
703
|
+
if (!hasDefault(field)) return "";
|
|
704
|
+
return " = null";
|
|
705
|
+
};
|
|
649
706
|
const optionalize = (type, optional) => {
|
|
650
707
|
if (!optional) return type;
|
|
651
708
|
return type.endsWith("?") ? type : `${type}?`;
|
|
@@ -661,9 +718,12 @@ const KOTLIN_PRIMITIVE_TYPES = new Set([
|
|
|
661
718
|
"ByteArray"
|
|
662
719
|
]);
|
|
663
720
|
/**
|
|
664
|
-
* How a response body is read. Raw bytes are the body already.
|
|
721
|
+
* How a response body is read. Raw bytes are the body already, and text is its decoded bytes.
|
|
665
722
|
*/
|
|
666
|
-
const decodeBody = (resolved
|
|
723
|
+
const decodeBody = (resolved, isText = false) => {
|
|
724
|
+
if (resolved === "ByteArray") return "data";
|
|
725
|
+
return isText ? "data.decodeToString()" : `json.decodeFromString<${resolved}>(data.decodeToString())`;
|
|
726
|
+
};
|
|
667
727
|
const resolveType = (typeName, currentOperation, context, scope = "client") => {
|
|
668
728
|
const { operationTypeMap, namespaceName, clientName, fileLevelTypeNames } = context;
|
|
669
729
|
const optional = typeName.endsWith("?");
|
|
@@ -748,28 +808,28 @@ const enumConstantName = (value) => {
|
|
|
748
808
|
const emitEnumClass = (writer, name, cases, unknownCase, description) => {
|
|
749
809
|
writer.blank();
|
|
750
810
|
writer.docComment(description);
|
|
811
|
+
const constants = (0, kizunajs_generator.uniqueNames)(cases.map(enumConstantName));
|
|
751
812
|
if (!unknownCase) {
|
|
752
813
|
writer.line("@Serializable");
|
|
753
814
|
writer.block(`enum class ${name}(override val wireValue: String) : KizunaQueryValue`, () => {
|
|
754
815
|
for (let index = 0; index < cases.length; index += 1) {
|
|
755
816
|
const caseName = cases[index];
|
|
756
|
-
const enumConstant = enumConstantName(caseName);
|
|
757
817
|
const separator = index < cases.length - 1 ? "," : "";
|
|
758
|
-
writer.line(`@SerialName(${stringLiteral(caseName)}) ${
|
|
818
|
+
writer.line(`@SerialName(${stringLiteral(caseName)}) ${constants[index]}(${stringLiteral(caseName)})${separator}`);
|
|
759
819
|
}
|
|
760
820
|
});
|
|
761
821
|
return;
|
|
762
822
|
}
|
|
763
823
|
writer.line(`@Serializable(with = ${name}.Serializer::class)`);
|
|
764
824
|
writer.block(`sealed interface ${name} : KizunaQueryValue`, () => {
|
|
765
|
-
for (
|
|
766
|
-
writer.line(`override val wireValue: String = ${stringLiteral(
|
|
825
|
+
for (let index = 0; index < cases.length; index += 1) writer.block(`data object ${constants[index]} : ${name}`, () => {
|
|
826
|
+
writer.line(`override val wireValue: String = ${stringLiteral(cases[index])}`);
|
|
767
827
|
});
|
|
768
828
|
writer.line(`data class Unknown(override val wireValue: String) : ${name}`);
|
|
769
829
|
writer.blank();
|
|
770
830
|
writer.block("companion object", () => {
|
|
771
831
|
writer.block(`fun fromWireValue(wireValue: String): ${name} = when (wireValue)`, () => {
|
|
772
|
-
for (
|
|
832
|
+
for (let index = 0; index < cases.length; index += 1) writer.line(`${stringLiteral(cases[index])} -> ${constants[index]}`);
|
|
773
833
|
writer.line("else -> Unknown(wireValue)");
|
|
774
834
|
});
|
|
775
835
|
});
|
|
@@ -783,7 +843,7 @@ const emitEnumClass = (writer, name, cases, unknownCase, description) => {
|
|
|
783
843
|
});
|
|
784
844
|
});
|
|
785
845
|
};
|
|
786
|
-
const emitDataClass = (writer, type, ownedTypeMap, ownedTypeLookup, registryName) => {
|
|
846
|
+
const emitDataClass = (writer, type, ownedTypeMap, ownedTypeLookup, registryName, registry, withBuilders = false) => {
|
|
787
847
|
const lookupName = registryName ?? type.name;
|
|
788
848
|
const baseFields = type.discriminatorWireName ? type.fields.filter((field) => field.wireName !== type.discriminatorWireName) : type.fields;
|
|
789
849
|
const hasFile = baseFields.some((field) => field.isFile);
|
|
@@ -806,7 +866,7 @@ const emitDataClass = (writer, type, ownedTypeMap, ownedTypeLookup, registryName
|
|
|
806
866
|
if (!hasFile) writer.line("@Serializable");
|
|
807
867
|
const params = adjustedFields.map((field) => {
|
|
808
868
|
const typeExpression = optionalize(field.type, field.optional);
|
|
809
|
-
const defaultPart = field
|
|
869
|
+
const defaultPart = defaultArgument(field);
|
|
810
870
|
const serialNameAnnotation = needsSerialName && (field.name !== field.wireName || KOTLIN_KEYWORDS.has(field.name)) ? `@SerialName(${stringLiteral(field.wireName)}) ` : "";
|
|
811
871
|
return `${field.deprecated ? `${deprecatedAnnotation(field.deprecationMessage)} ` : ""}${serialNameAnnotation}val ${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
|
|
812
872
|
});
|
|
@@ -824,15 +884,86 @@ const emitDataClass = (writer, type, ownedTypeMap, ownedTypeLookup, registryName
|
|
|
824
884
|
writer.line(")");
|
|
825
885
|
}
|
|
826
886
|
if (type.sealedParent !== void 0) writer.appendToLastLine(` : ${type.sealedParent}`);
|
|
827
|
-
|
|
887
|
+
const builds = withBuilders && !hasFile && isBuilderModel(type);
|
|
888
|
+
if (hasOwnedTypes || builds) {
|
|
828
889
|
writer.appendToLastLine(" {");
|
|
829
890
|
writer.indent(() => {
|
|
830
|
-
emitOwnedTypes(writer, lookupName, ownedTypeMap, ownedTypeLookup);
|
|
891
|
+
if (hasOwnedTypes) emitOwnedTypes(writer, lookupName, ownedTypeMap, ownedTypeLookup, registry, withBuilders);
|
|
892
|
+
if (builds) {
|
|
893
|
+
const lookup = (name) => registry?.get(name) ?? ownedTypeLookup.get(name);
|
|
894
|
+
emitBuilders(writer, type.name, adjustedFields, baseFields, lookup);
|
|
895
|
+
}
|
|
831
896
|
});
|
|
832
897
|
writer.line("}");
|
|
833
898
|
}
|
|
834
899
|
};
|
|
835
|
-
|
|
900
|
+
/**
|
|
901
|
+
* A data class whose fields are all optional, so it can be written one field at a time.
|
|
902
|
+
*/
|
|
903
|
+
const isBuilderModel = (type) => type?.kind === "data-class" && type.sealedParent === void 0 && type.discriminatorWireName === void 0 && type.fields.length > 0 && type.fields.every((field) => field.optional && field.requiredNullable !== true && field.isFile !== true);
|
|
904
|
+
/**
|
|
905
|
+
* What a field holds: one value or a list of them, and the type named inside.
|
|
906
|
+
*/
|
|
907
|
+
const fieldTarget = (fieldType) => {
|
|
908
|
+
const stripped = fieldType.endsWith("?") ? fieldType.slice(0, -1) : fieldType;
|
|
909
|
+
const list = stripped.startsWith("List<") && stripped.endsWith(">");
|
|
910
|
+
return {
|
|
911
|
+
list,
|
|
912
|
+
inner: list ? stripped.slice(5, -1) : stripped
|
|
913
|
+
};
|
|
914
|
+
};
|
|
915
|
+
/**
|
|
916
|
+
* `Builder` writes one of these field by field and `ListBuilder` a list of them, one block per item:
|
|
917
|
+
* `where { or { name { contains = "ada" } } }`.
|
|
918
|
+
*/
|
|
919
|
+
const emitBuilders = (writer, className, fields, rawFields, lookup) => {
|
|
920
|
+
const targets = fields.map((field, index) => {
|
|
921
|
+
const { list, inner } = fieldTarget(field.type);
|
|
922
|
+
return {
|
|
923
|
+
name: escapeKeyword(field.name),
|
|
924
|
+
type: field.type,
|
|
925
|
+
list,
|
|
926
|
+
inner,
|
|
927
|
+
buildable: isBuilderModel(lookup(fieldTarget(rawFields[index].type).inner))
|
|
928
|
+
};
|
|
929
|
+
});
|
|
930
|
+
const blockOf = (target) => `${target.inner}.${target.list ? "ListBuilder" : "Builder"}`;
|
|
931
|
+
writer.blank();
|
|
932
|
+
writer.line("@KizunaDsl");
|
|
933
|
+
writer.block("class Builder", () => {
|
|
934
|
+
for (const target of targets) writer.line(`var ${target.name}: ${optionalize(target.type, true)} = null`);
|
|
935
|
+
for (const target of targets) {
|
|
936
|
+
if (!target.buildable) continue;
|
|
937
|
+
writer.blank();
|
|
938
|
+
writer.block(`fun ${target.name}(build: ${blockOf(target)}.() -> Unit)`, () => {
|
|
939
|
+
writer.line(`${target.name} = ${blockOf(target)}().apply(build).build()`);
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
writer.blank();
|
|
943
|
+
writer.line(`fun build(): ${className} = ${className}(${targets.map((target) => `${target.name} = ${target.name}`).join(", ")})`);
|
|
944
|
+
});
|
|
945
|
+
writer.blank();
|
|
946
|
+
writer.line("@KizunaDsl");
|
|
947
|
+
writer.block("class ListBuilder", () => {
|
|
948
|
+
writer.line(`private val items = mutableListOf<${className}>()`);
|
|
949
|
+
writer.blank();
|
|
950
|
+
writer.block(`fun add(item: ${className})`, () => {
|
|
951
|
+
writer.line("items += item");
|
|
952
|
+
});
|
|
953
|
+
for (const target of targets) {
|
|
954
|
+
writer.blank();
|
|
955
|
+
if (target.buildable) writer.block(`fun ${target.name}(build: ${blockOf(target)}.() -> Unit)`, () => {
|
|
956
|
+
writer.line(`items += ${className}(${target.name} = ${blockOf(target)}().apply(build).build())`);
|
|
957
|
+
});
|
|
958
|
+
else writer.block(`fun ${target.name}(value: ${optionalize(target.type, false)})`, () => {
|
|
959
|
+
writer.line(`items += ${className}(${target.name} = value)`);
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
writer.blank();
|
|
963
|
+
writer.line(`fun build(): List<${className}> = items.toList()`);
|
|
964
|
+
});
|
|
965
|
+
};
|
|
966
|
+
const emitOwnedTypes = (writer, ownerName, ownedTypeMap, ownedTypeLookup, registry, withBuilders = false) => {
|
|
836
967
|
for (const [ownedName, owningType] of ownedTypeMap) {
|
|
837
968
|
if (owningType !== ownerName) continue;
|
|
838
969
|
const ownedType = ownedTypeLookup.get(ownedName);
|
|
@@ -841,7 +972,7 @@ const emitOwnedTypes = (writer, ownerName, ownedTypeMap, ownedTypeLookup, regist
|
|
|
841
972
|
emitType(writer, {
|
|
842
973
|
...ownedType,
|
|
843
974
|
name: shortName
|
|
844
|
-
}, ownedTypeMap, ownedTypeLookup, ownedName, registry);
|
|
975
|
+
}, ownedTypeMap, ownedTypeLookup, ownedName, registry, withBuilders);
|
|
845
976
|
}
|
|
846
977
|
};
|
|
847
978
|
const relativeOwnedPath = (typeName, ownedTypeMap, enclosingPath, registry) => {
|
|
@@ -857,11 +988,14 @@ const ownedTypePath = (typeName, ownedTypeMap, registry) => {
|
|
|
857
988
|
return `${ownedTypePath(owningClass, ownedTypeMap, registry)}.${(0, kizunajs_generator.shortTypeName)(typeName, owningClass)}`;
|
|
858
989
|
};
|
|
859
990
|
const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup) => {
|
|
860
|
-
writer.line(`@
|
|
861
|
-
|
|
862
|
-
|
|
991
|
+
if (type.unknownCase) writer.line(`@Serializable(with = ${type.name}.Serializer::class)`);
|
|
992
|
+
else {
|
|
993
|
+
writer.line(`@OptIn(ExperimentalSerializationApi::class)`);
|
|
994
|
+
writer.line(`@JsonClassDiscriminator(${stringLiteral(type.discriminator)})`);
|
|
995
|
+
writer.line("@Serializable");
|
|
996
|
+
}
|
|
863
997
|
const nestedVariants = type.variants.filter((variant) => variant.nested);
|
|
864
|
-
if (nestedVariants.length === 0) {
|
|
998
|
+
if (nestedVariants.length === 0 && !type.unknownCase) {
|
|
865
999
|
writer.line(`sealed interface ${type.name}`);
|
|
866
1000
|
return;
|
|
867
1001
|
}
|
|
@@ -878,9 +1012,10 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
|
|
|
878
1012
|
})()
|
|
879
1013
|
}));
|
|
880
1014
|
const sharedFields = wrapped.length > 0 && wrapped.every(({ payload, inlined }) => payload !== void 0 && !inlined) ? wrapped[0].payload.fields.filter((field) => wrapped.every(({ payload }) => payload.fields.some((other) => other.name === field.name && other.type === field.type && other.optional === field.optional))) : [];
|
|
1015
|
+
const sharedOptional = (field) => field.optional || type.unknownCase && field.wireName !== type.discriminator;
|
|
881
1016
|
writer.block(`sealed interface ${type.name}`, () => {
|
|
882
1017
|
for (const field of sharedFields) {
|
|
883
|
-
const typeExpression = optionalize(ownedTypePath(field.type, ownedTypeMap, registry), field
|
|
1018
|
+
const typeExpression = optionalize(ownedTypePath(field.type, ownedTypeMap, registry), sharedOptional(field));
|
|
884
1019
|
writer.line(`val ${escapeKeyword(field.name)}: ${typeExpression}`);
|
|
885
1020
|
}
|
|
886
1021
|
if (sharedFields.length > 0) writer.blank();
|
|
@@ -899,7 +1034,7 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
|
|
|
899
1034
|
const params = fields.map((field) => {
|
|
900
1035
|
const variantPath = registry.sealedVariantPath(variant.payloadType) ?? variant.payloadType;
|
|
901
1036
|
const typeExpression = optionalize(relativeOwnedPath(field.type, ownedTypeMap, variantPath, registry) ?? ownedTypePath(field.type, ownedTypeMap, registry), field.optional);
|
|
902
|
-
const defaultPart = field
|
|
1037
|
+
const defaultPart = defaultArgument(field);
|
|
903
1038
|
return `val ${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
|
|
904
1039
|
});
|
|
905
1040
|
if (params.length === 1) writer.line(`data class ${variant.caseName}(${params[0]}) : ${type.name}`);
|
|
@@ -927,17 +1062,79 @@ const emitSealedClass = (writer, type, registry, ownedTypeMap, ownedTypeLookup)
|
|
|
927
1062
|
});
|
|
928
1063
|
else writer.line(`data class ${variant.caseName}(val value: ${ownedTypePath(variant.payloadType, ownedTypeMap, registry)}) : ${type.name}`);
|
|
929
1064
|
}
|
|
1065
|
+
if (type.unknownCase) emitUnknownVariant(writer, type, sharedFields, registry, ownedTypeMap);
|
|
1066
|
+
});
|
|
1067
|
+
};
|
|
1068
|
+
/**
|
|
1069
|
+
* A union's `Unknown` member and the serializer that falls back to it: it reads the discriminator, decodes the
|
|
1070
|
+
* matching variant from the rest of the object, and writes the discriminator back on encode.
|
|
1071
|
+
*/
|
|
1072
|
+
const emitUnknownVariant = (writer, type, sharedFields, registry, ownedTypeMap) => {
|
|
1073
|
+
const taken = new Set(type.variants.map((variant) => variant.caseName));
|
|
1074
|
+
let unknown = "Unknown";
|
|
1075
|
+
while (taken.has(unknown)) unknown = `${unknown}Variant`;
|
|
1076
|
+
const discriminator = stringLiteral(type.discriminator);
|
|
1077
|
+
const cases = type.variants.map((variant) => {
|
|
1078
|
+
const payload = registry.all().find((candidate) => candidate.name === variant.payloadType);
|
|
1079
|
+
const inline = payload !== void 0 && payload.kind === "data-class" && payload.fields.length > 0;
|
|
1080
|
+
const wrapped = variant.nested && !inline;
|
|
1081
|
+
return {
|
|
1082
|
+
literal: stringLiteral(variant.literal),
|
|
1083
|
+
className: variant.nested ? variant.caseName : ownedTypePath(variant.payloadType, ownedTypeMap, registry),
|
|
1084
|
+
payloadPath: ownedTypePath(variant.payloadType, ownedTypeMap, registry),
|
|
1085
|
+
wrapped
|
|
1086
|
+
};
|
|
1087
|
+
});
|
|
1088
|
+
writer.blank();
|
|
1089
|
+
writer.docComment("A variant this client was generated before. It holds the discriminator, and cannot be sent back.");
|
|
1090
|
+
const overrides = sharedFields.map((field) => field.wireName === type.discriminator ? `override val ${escapeKeyword(field.name)}: String get() = wireValue` : `override val ${escapeKeyword(field.name)}: ${optionalize(ownedTypePath(field.type, ownedTypeMap, registry), true)} get() = null`);
|
|
1091
|
+
if (overrides.length === 0) writer.line(`data class ${unknown}(val wireValue: String) : ${type.name}`);
|
|
1092
|
+
else writer.block(`data class ${unknown}(val wireValue: String) : ${type.name}`, () => {
|
|
1093
|
+
for (const line of overrides) writer.line(line);
|
|
1094
|
+
});
|
|
1095
|
+
writer.blank();
|
|
1096
|
+
writer.block(`object Serializer : KSerializer<${type.name}>`, () => {
|
|
1097
|
+
writer.line(`override val descriptor: SerialDescriptor = buildClassSerialDescriptor(${stringLiteral(type.name)})`);
|
|
1098
|
+
writer.blank();
|
|
1099
|
+
writer.block(`override fun deserialize(decoder: Decoder): ${type.name}`, () => {
|
|
1100
|
+
writer.line("val input = decoder as JsonDecoder");
|
|
1101
|
+
writer.line("val element = input.decodeJsonElement().jsonObject");
|
|
1102
|
+
writer.line(`val body = JsonObject(element - ${discriminator})`);
|
|
1103
|
+
writer.block(`return when (val kind = element[${discriminator}]?.jsonPrimitive?.contentOrNull)`, () => {
|
|
1104
|
+
for (const each of cases) writer.line(each.wrapped ? `${each.literal} -> ${each.className}(input.json.decodeFromJsonElement(${each.payloadPath}.serializer(), body))` : `${each.literal} -> input.json.decodeFromJsonElement(${each.className}.serializer(), body)`);
|
|
1105
|
+
writer.line(`else -> ${unknown}(kind ?: "")`);
|
|
1106
|
+
});
|
|
1107
|
+
});
|
|
1108
|
+
writer.blank();
|
|
1109
|
+
writer.block(`override fun serialize(encoder: Encoder, value: ${type.name})`, () => {
|
|
1110
|
+
writer.line("val output = encoder as JsonEncoder");
|
|
1111
|
+
writer.block("val (kind, body) = when (value)", () => {
|
|
1112
|
+
for (const each of cases) writer.line(each.wrapped ? `is ${each.className} -> ${each.literal} to output.json.encodeToJsonElement(${each.payloadPath}.serializer(), value.value)` : `is ${each.className} -> ${each.literal} to output.json.encodeToJsonElement(${each.className}.serializer(), value)`);
|
|
1113
|
+
writer.line(`is ${unknown} -> throw SerializationException("This client does not know the variant \${value.wireValue}, so it cannot send it.")`);
|
|
1114
|
+
});
|
|
1115
|
+
writer.line(`output.encodeJsonElement(JsonObject(mapOf(${discriminator} to JsonPrimitive(kind)) + body.jsonObject))`);
|
|
1116
|
+
});
|
|
930
1117
|
});
|
|
931
1118
|
};
|
|
932
|
-
const emitType = (writer, type, ownedTypeMap = /* @__PURE__ */ new Map(), ownedTypeLookup = /* @__PURE__ */ new Map(), registryName, registry) => {
|
|
1119
|
+
const emitType = (writer, type, ownedTypeMap = /* @__PURE__ */ new Map(), ownedTypeLookup = /* @__PURE__ */ new Map(), registryName, registry, withBuilders = false) => {
|
|
933
1120
|
writer.blank();
|
|
934
1121
|
writer.docComment(type.description);
|
|
935
|
-
if (type.kind === "data-class") emitDataClass(writer, type, ownedTypeMap, ownedTypeLookup, registryName);
|
|
1122
|
+
if (type.kind === "data-class") emitDataClass(writer, type, ownedTypeMap, ownedTypeLookup, registryName, registry, withBuilders);
|
|
936
1123
|
else if (type.kind === "enum-class") emitEnumClass(writer, type.name, type.cases, type.unknownCase, type.description);
|
|
937
1124
|
else if (registry) emitSealedClass(writer, type, registry, ownedTypeMap, ownedTypeLookup);
|
|
938
1125
|
};
|
|
939
|
-
|
|
940
|
-
|
|
1126
|
+
/**
|
|
1127
|
+
* A brand as a value class that serializes and prints as the bare value.
|
|
1128
|
+
*/
|
|
1129
|
+
const emitBrand = (writer, brand) => {
|
|
1130
|
+
writer.line("@Serializable");
|
|
1131
|
+
writer.line("@JvmInline");
|
|
1132
|
+
writer.block(`value class ${brand.name}(val value: ${brand.rawType})`, () => {
|
|
1133
|
+
writer.line(`override fun toString(): String = ${brand.rawType === "String" ? "value" : "value.toString()"}`);
|
|
1134
|
+
});
|
|
1135
|
+
};
|
|
1136
|
+
const emitTypes = (writer, types, ownedTypeMap = /* @__PURE__ */ new Map(), ownedTypeLookup = /* @__PURE__ */ new Map(), registry, withBuilders = false) => {
|
|
1137
|
+
for (const type of types) emitType(writer, type, ownedTypeMap, ownedTypeLookup, void 0, registry, withBuilders);
|
|
941
1138
|
};
|
|
942
1139
|
const emitConstructorClass = (writer, declaration, params) => {
|
|
943
1140
|
if (params.length === 1) writer.line(`${declaration}(${params[0]})`);
|
|
@@ -993,7 +1190,9 @@ const emitOperationResultTypes = (writer, method, context) => {
|
|
|
993
1190
|
const streamEvents = method.stream?.events;
|
|
994
1191
|
if (streamEvents) {
|
|
995
1192
|
const eventNames = new Set(streamEvents.map((event) => event.name));
|
|
996
|
-
|
|
1193
|
+
const tracksTools = eventNames.has("tool_call") && eventNames.has("tool_result");
|
|
1194
|
+
const readId = (eventName) => `val id = event.data.id${streamEvents.find((event) => event.name === eventName)?.unknownCase ? " ?: continue" : ""}`;
|
|
1195
|
+
if (tracksTools) {
|
|
997
1196
|
writer.blank();
|
|
998
1197
|
writer.line("/** One tool call, with its result once it answered. */");
|
|
999
1198
|
writer.line("data class ToolCallRecord(");
|
|
@@ -1011,7 +1210,7 @@ const emitOperationResultTypes = (writer, method, context) => {
|
|
|
1011
1210
|
writer.line(") {");
|
|
1012
1211
|
writer.indent(() => {
|
|
1013
1212
|
writer.line("/** How far along the call is. */");
|
|
1014
|
-
writer.line("enum class State { Running, Done, Failed }");
|
|
1213
|
+
writer.line("enum class State { Running, NeedsApproval, Done, Failed }");
|
|
1015
1214
|
});
|
|
1016
1215
|
writer.line("}");
|
|
1017
1216
|
writer.blank();
|
|
@@ -1021,8 +1220,19 @@ const emitOperationResultTypes = (writer, method, context) => {
|
|
|
1021
1220
|
writer.block("for (event in events)", () => {
|
|
1022
1221
|
writer.line("when (event) {");
|
|
1023
1222
|
writer.indent(() => {
|
|
1024
|
-
writer.line("is Event.ToolCall ->
|
|
1025
|
-
writer.
|
|
1223
|
+
writer.line("is Event.ToolCall -> {");
|
|
1224
|
+
writer.indent(() => {
|
|
1225
|
+
writer.line(readId("tool_call"));
|
|
1226
|
+
writer.line("val tracked = (calls[id] ?: ToolCallRecord(id, event.data.name)).copy(call = event.data)");
|
|
1227
|
+
writer.line("calls[id] = if (event.data.needsApproval == true && tracked.state == ToolCallRecord.State.Running) tracked.copy(state = ToolCallRecord.State.NeedsApproval) else tracked");
|
|
1228
|
+
});
|
|
1229
|
+
writer.line("}");
|
|
1230
|
+
writer.line("is Event.ToolResult -> {");
|
|
1231
|
+
writer.indent(() => {
|
|
1232
|
+
writer.line(readId("tool_result"));
|
|
1233
|
+
writer.line("calls[id] = (calls[id] ?: ToolCallRecord(id, event.data.name)).copy(state = ToolCallRecord.State.Done, result = event.data)");
|
|
1234
|
+
});
|
|
1235
|
+
writer.line("}");
|
|
1026
1236
|
if (eventNames.has("tool_error")) writer.line("is Event.ToolError -> calls[event.data.id] = (calls[event.data.id] ?: ToolCallRecord(event.data.id, event.data.name.wireValue)).copy(state = ToolCallRecord.State.Failed, message = event.data.message)");
|
|
1027
1237
|
writer.line("else -> Unit");
|
|
1028
1238
|
});
|
|
@@ -1083,7 +1293,7 @@ const groupTypeRef = (operationName, className, context) => `${context.clientNam
|
|
|
1083
1293
|
const groupMemberAccessor = (groupLabel, field) => `${groupLabel}.${escapeKeyword(field.name)}`;
|
|
1084
1294
|
const groupClassField = (field) => {
|
|
1085
1295
|
const typeExpression = optionalize(field.type, field.optional);
|
|
1086
|
-
const defaultPart = field
|
|
1296
|
+
const defaultPart = defaultArgument(field);
|
|
1087
1297
|
return `val ${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
|
|
1088
1298
|
};
|
|
1089
1299
|
const emitGroupClass = (writer, className, fields, method, context) => {
|
|
@@ -1142,13 +1352,13 @@ const methodChannels = (method) => {
|
|
|
1142
1352
|
if (method.query.length > 0) channels.push({
|
|
1143
1353
|
varName: "query",
|
|
1144
1354
|
className: "Query",
|
|
1145
|
-
required: method.query.some((field) => !field
|
|
1355
|
+
required: method.query.some((field) => !hasDefault(field)),
|
|
1146
1356
|
fields: method.query
|
|
1147
1357
|
});
|
|
1148
1358
|
if (method.headers.length > 0) channels.push({
|
|
1149
1359
|
varName: "headers",
|
|
1150
1360
|
className: "Headers",
|
|
1151
|
-
required: method.headers.some((field) => !field
|
|
1361
|
+
required: method.headers.some((field) => !hasDefault(field)),
|
|
1152
1362
|
fields: method.headers
|
|
1153
1363
|
});
|
|
1154
1364
|
if (hasBodyGroup(method)) {
|
|
@@ -1197,7 +1407,7 @@ const emitArgsScaffolding = (writer, method, context) => {
|
|
|
1197
1407
|
};
|
|
1198
1408
|
const factorySignature = (channel) => channel.fields.map((field) => {
|
|
1199
1409
|
const typeExpression = optionalize(field.type, field.optional);
|
|
1200
|
-
const defaultPart = field
|
|
1410
|
+
const defaultPart = defaultArgument(field);
|
|
1201
1411
|
return `${escapeKeyword(field.name)}: ${typeExpression}${defaultPart}`;
|
|
1202
1412
|
}).join(", ");
|
|
1203
1413
|
const factoryConstruction = (channel) => {
|
|
@@ -1218,9 +1428,20 @@ const emitArgsScaffolding = (writer, method, context) => {
|
|
|
1218
1428
|
writer.block("sealed interface Args", () => {
|
|
1219
1429
|
for (const channel of channels) writer.line(`val ${channel.varName}: ${channel.className}${channel.required ? "" : "?"}`);
|
|
1220
1430
|
});
|
|
1431
|
+
const namespacePrefix = `${context.namespaceName}.`;
|
|
1432
|
+
const buildableQueryFields = (channels.find((channel) => channel.varName === "query")?.fields ?? []).flatMap((field) => {
|
|
1433
|
+
const { list, inner } = fieldTarget(field.type);
|
|
1434
|
+
const name = inner.startsWith(namespacePrefix) ? inner.slice(namespacePrefix.length) : inner;
|
|
1435
|
+
return context.builderModelNames.has(name) ? [{
|
|
1436
|
+
field,
|
|
1437
|
+
block: `${inner}.${list ? "ListBuilder" : "Builder"}`,
|
|
1438
|
+
result: list ? `List<${inner}>` : inner
|
|
1439
|
+
}] : [];
|
|
1440
|
+
});
|
|
1221
1441
|
writer.blank();
|
|
1222
1442
|
writer.block("object Scope", () => {
|
|
1223
1443
|
for (const target of transitionsFrom(-1)) emitTransition(-1, target);
|
|
1444
|
+
for (const { field, block, result } of buildableQueryFields) writer.line(`fun ${escapeKeyword(field.name)}(build: ${block}.() -> Unit): ${result} = ${block}().apply(build).build()`);
|
|
1224
1445
|
});
|
|
1225
1446
|
for (let stateIndex = 0; stateIndex < channels.length; stateIndex += 1) {
|
|
1226
1447
|
const stateChannel = channels[stateIndex];
|
|
@@ -1254,10 +1475,16 @@ const emitBodyEncoding = (writer, method, context) => {
|
|
|
1254
1475
|
if (body.kind === "multipart") {
|
|
1255
1476
|
writer.line("val multipartBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)");
|
|
1256
1477
|
for (const field of body.multipartFields) {
|
|
1257
|
-
const
|
|
1258
|
-
const
|
|
1259
|
-
|
|
1260
|
-
|
|
1478
|
+
const flattenedField = body.flattened.find((flatField) => flatField.name === field.name);
|
|
1479
|
+
const isFile = field.isFile || flattenedField?.isFile === true;
|
|
1480
|
+
const append = (accessor) => {
|
|
1481
|
+
if (isFile) writer.line(`multipartBuilder.addFormDataPart(${stringLiteral(field.wireName)}, ${accessor}.filename, ${accessor}.data.toRequestBody(${accessor}.mimeType.toMediaType()))`);
|
|
1482
|
+
else writer.line(`multipartBuilder.addFormDataPart(${stringLiteral(field.wireName)}, ${accessor}.toString())`);
|
|
1483
|
+
};
|
|
1484
|
+
if (flattenedField?.optional === true) writer.block(`if (${groupMemberAccessor("body", field)} != null)`, () => {
|
|
1485
|
+
append(groupMemberAccessor("body", field));
|
|
1486
|
+
});
|
|
1487
|
+
else append(groupMemberAccessor("body", field));
|
|
1261
1488
|
}
|
|
1262
1489
|
writer.line("requestBody = multipartBuilder.build()");
|
|
1263
1490
|
return;
|
|
@@ -1302,6 +1529,10 @@ const emitMethodBody = (writer, method, context) => {
|
|
|
1302
1529
|
if (method.query.length > 0) for (const field of method.query) {
|
|
1303
1530
|
const accessor = groupMemberAccessor("query", field);
|
|
1304
1531
|
const appendBlock = (sourceExpression) => {
|
|
1532
|
+
if (field.json) {
|
|
1533
|
+
writer.line(`urlBuilder.addQueryParameter(${stringLiteral(field.wireName)}, Kizuna.encodeQueryJson(json, ${sourceExpression}))`);
|
|
1534
|
+
return;
|
|
1535
|
+
}
|
|
1305
1536
|
writer.block(`for (stringValue in Kizuna.stringifyQueryValue(${sourceExpression}))`, () => {
|
|
1306
1537
|
writer.line(`urlBuilder.addQueryParameter(${stringLiteral(field.wireName)}, stringValue)`);
|
|
1307
1538
|
});
|
|
@@ -1333,7 +1564,7 @@ const emitMethodBody = (writer, method, context) => {
|
|
|
1333
1564
|
else setHeader(accessor);
|
|
1334
1565
|
}
|
|
1335
1566
|
writer.line("requestInterceptor?.invoke(requestBuilder)");
|
|
1336
|
-
writer.line("val httpResponse = Kizuna.
|
|
1567
|
+
writer.line("val httpResponse = Kizuna.send(client, requestBuilder.build(), retry)");
|
|
1337
1568
|
if (method.stream) {
|
|
1338
1569
|
emitStreamMethodTail(writer, method, context);
|
|
1339
1570
|
return;
|
|
@@ -1353,7 +1584,7 @@ const emitMethodBody = (writer, method, context) => {
|
|
|
1353
1584
|
writer.indent(() => {
|
|
1354
1585
|
const resolved = resolveType(successResponse.type, method.operationName, context);
|
|
1355
1586
|
writer.block("try", () => {
|
|
1356
|
-
writer.line(`val payload = ${decodeBody(resolved)}`);
|
|
1587
|
+
writer.line(`val payload = ${decodeBody(resolved, successResponse.isText)}`);
|
|
1357
1588
|
const bodyExpr = isMultiSuccess ? `${operationRef}.Success.Status${successResponse.status}(payload)` : "payload";
|
|
1358
1589
|
if (hasHeaders) {
|
|
1359
1590
|
for (const field of successResponse.responseHeaders) writer.line(`val ${escapeKeyword(field.name)} = httpResponse.header(${stringLiteral(field.wireName)})`);
|
|
@@ -1416,6 +1647,35 @@ const emitErrorBranches = (writer, method, context) => {
|
|
|
1416
1647
|
}
|
|
1417
1648
|
writer.line(`else -> throw ${failureRef}.Unexpected(statusCode = statusCode, data = data)`);
|
|
1418
1649
|
};
|
|
1650
|
+
const IDEMPOTENT_METHODS = new Set([
|
|
1651
|
+
"GET",
|
|
1652
|
+
"HEAD",
|
|
1653
|
+
"OPTIONS",
|
|
1654
|
+
"PUT",
|
|
1655
|
+
"DELETE"
|
|
1656
|
+
]);
|
|
1657
|
+
/**
|
|
1658
|
+
* Writes the reconnection an event stream reopens through and returns the argument handing it to `Kizuna.events`, or
|
|
1659
|
+
* nothing for a method a client may not resend.
|
|
1660
|
+
*/
|
|
1661
|
+
const emitReopen = (writer, method, operationRef, status) => {
|
|
1662
|
+
if (!IDEMPOTENT_METHODS.has(method.method)) return "";
|
|
1663
|
+
closure(writer, "val reconnection = reconnect?.let { policy ->", () => {
|
|
1664
|
+
closure(writer, "Kizuna.Reconnection(policy) { lastEventId ->", () => {
|
|
1665
|
+
writer.line("val again = requestBuilder.build().newBuilder()");
|
|
1666
|
+
writer.line("if (lastEventId.isNotEmpty()) again.header(\"Last-Event-ID\", lastEventId)");
|
|
1667
|
+
writer.line("requestInterceptor?.invoke(again)");
|
|
1668
|
+
writer.line("val reopened = Kizuna.send(client, again.build(), retry)");
|
|
1669
|
+
writer.line("val eventStream = reopened.header(\"Content-Type\")?.lowercase()?.startsWith(\"text/event-stream\") == true");
|
|
1670
|
+
writer.block("when", () => {
|
|
1671
|
+
writer.line("reopened.code == 204 -> { reopened.close(); null }");
|
|
1672
|
+
writer.line(`reopened.code == ${status} && eventStream -> reopened`);
|
|
1673
|
+
writer.line(`else -> { reopened.close(); throw ${operationRef}.Failure.Unexpected(statusCode = reopened.code, data = ByteArray(0)) }`);
|
|
1674
|
+
});
|
|
1675
|
+
});
|
|
1676
|
+
});
|
|
1677
|
+
return ", reconnection";
|
|
1678
|
+
};
|
|
1419
1679
|
const emitStreamMethodTail = (writer, method, context) => {
|
|
1420
1680
|
const operationRef = `${context.clientName}.${method.operationName}`;
|
|
1421
1681
|
const stream = method.stream;
|
|
@@ -1428,7 +1688,7 @@ const emitStreamMethodTail = (writer, method, context) => {
|
|
|
1428
1688
|
else if (stream.events) {
|
|
1429
1689
|
const events = stream.events;
|
|
1430
1690
|
const elementType = streamElementType(method, context, "client");
|
|
1431
|
-
closure(writer, `val body = Kizuna.events<${elementType}>(httpResponse) { event ->`, () => {
|
|
1691
|
+
closure(writer, `val body = Kizuna.events<${elementType}>(httpResponse${emitReopen(writer, method, operationRef, stream.status)}) { event ->`, () => {
|
|
1432
1692
|
writer.block("when (event.event)", () => {
|
|
1433
1693
|
for (const event of events) {
|
|
1434
1694
|
const payloadType = resolveType(event.type, method.operationName, context);
|
|
@@ -1439,7 +1699,8 @@ const emitStreamMethodTail = (writer, method, context) => {
|
|
|
1439
1699
|
});
|
|
1440
1700
|
} else {
|
|
1441
1701
|
const elementType = streamElementType(method, context, "client");
|
|
1442
|
-
|
|
1702
|
+
const reconnection = emitReopen(writer, method, operationRef, stream.status);
|
|
1703
|
+
writer.line(`val body = Kizuna.events<${elementType}>(httpResponse${reconnection}) { event -> json.decodeFromString<${elementType}>(event.data) }`);
|
|
1443
1704
|
}
|
|
1444
1705
|
if (hasHeaders) {
|
|
1445
1706
|
for (const field of successResponse.responseHeaders) writer.line(`val ${escapeKeyword(field.name)} = httpResponse.header(${stringLiteral(field.wireName)})`);
|
|
@@ -1485,7 +1746,7 @@ const emitSubClientMethod = (writer, method, context) => {
|
|
|
1485
1746
|
};
|
|
1486
1747
|
const emitSubClientClass = (writer, group, clientName, context) => {
|
|
1487
1748
|
writer.blank();
|
|
1488
|
-
writer.block(`class ${group.className}(private val client: OkHttpClient, private val baseUrl: String, private val json: Json, private val requestContextHeaders: Map<String, String>, private val requestInterceptor: (suspend (Request.Builder) -> Unit)?, private val responseInterceptor: (suspend (Request, Response) -> Unit)?)`, () => {
|
|
1749
|
+
writer.block(`class ${group.className}(private val client: OkHttpClient, private val baseUrl: String, private val json: Json, private val requestContextHeaders: Map<String, String>, private val requestInterceptor: (suspend (Request.Builder) -> Unit)?, private val responseInterceptor: (suspend (Request, Response) -> Unit)?, private val retry: ${clientName}.RetryPolicy?, private val reconnect: ${clientName}.ReconnectPolicy?)`, () => {
|
|
1489
1750
|
for (const method of group.methods) {
|
|
1490
1751
|
writer.blank();
|
|
1491
1752
|
emitSubClientMethod(writer, method, context);
|
|
@@ -1497,10 +1758,12 @@ const closure = (writer, opener, body) => {
|
|
|
1497
1758
|
writer.indent(body);
|
|
1498
1759
|
writer.line("}");
|
|
1499
1760
|
};
|
|
1500
|
-
const emitKizunaStreaming = (writer) => {
|
|
1761
|
+
const emitKizunaStreaming = (writer, clientName) => {
|
|
1501
1762
|
writer.blank();
|
|
1502
1763
|
writer.line("data class ServerSentEvent(val event: String?, val data: String, val id: String?, val retry: Int?)");
|
|
1503
1764
|
writer.blank();
|
|
1765
|
+
writer.line(`class Reconnection(val policy: ${clientName}.ReconnectPolicy, val reopen: suspend (String) -> Response?)`);
|
|
1766
|
+
writer.blank();
|
|
1504
1767
|
writer.block("private suspend fun readLine(source: okio.BufferedSource): String?", () => {
|
|
1505
1768
|
writer.line("return kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { source.readUtf8Line() }");
|
|
1506
1769
|
});
|
|
@@ -1527,44 +1790,83 @@ const emitKizunaStreaming = (writer) => {
|
|
|
1527
1790
|
});
|
|
1528
1791
|
});
|
|
1529
1792
|
writer.blank();
|
|
1530
|
-
writer.
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
writer.line("val
|
|
1535
|
-
writer.
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
writer.
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1793
|
+
writer.line("private val LINE_ENDINGS = okio.ByteString.of('\\r'.code.toByte(), '\\n'.code.toByte())");
|
|
1794
|
+
writer.blank();
|
|
1795
|
+
writer.block("private suspend fun readEventLine(source: okio.BufferedSource): String?", () => {
|
|
1796
|
+
closure(writer, "return kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {", () => {
|
|
1797
|
+
writer.line("val end = source.indexOfElement(LINE_ENDINGS)");
|
|
1798
|
+
writer.block("if (end == -1L)", () => {
|
|
1799
|
+
writer.line("if (source.exhausted()) null else source.readUtf8()");
|
|
1800
|
+
});
|
|
1801
|
+
writer.block("else", () => {
|
|
1802
|
+
writer.line("val line = source.readUtf8(end)");
|
|
1803
|
+
writer.line("val carriageReturn = source.readByte() == '\\r'.code.toByte()");
|
|
1804
|
+
writer.line("if (carriageReturn && source.request(1) && source.buffer[0] == '\\n'.code.toByte()) source.skip(1)");
|
|
1805
|
+
writer.line("line");
|
|
1806
|
+
});
|
|
1807
|
+
});
|
|
1808
|
+
});
|
|
1809
|
+
writer.blank();
|
|
1810
|
+
writer.block("fun serverSentEvents(response: Response, reconnect: Reconnection?): Flow<ServerSentEvent> = flow", () => {
|
|
1811
|
+
writer.line("var lastEventId = \"\"");
|
|
1812
|
+
writer.line("var reconnectionTime = reconnect?.policy?.reconnectionTime ?: 3.seconds");
|
|
1813
|
+
writer.line("var current: Response? = response");
|
|
1814
|
+
writer.line("var attempts = 0");
|
|
1815
|
+
writer.line("var failure: Throwable? = null");
|
|
1816
|
+
writer.block("while (true)", () => {
|
|
1817
|
+
closure(writer, "current?.use { open ->", () => {
|
|
1818
|
+
writer.line("val source = open.body?.source() ?: return@use");
|
|
1819
|
+
writer.line("var eventType = \"\"");
|
|
1820
|
+
writer.line("val dataLines = mutableListOf<String>()");
|
|
1821
|
+
writer.line("var pendingId = lastEventId");
|
|
1822
|
+
writer.line("var retry: Int? = null");
|
|
1823
|
+
writer.line("var firstLine = true");
|
|
1824
|
+
writer.block("while (true)", () => {
|
|
1825
|
+
writer.line("val received = try { readEventLine(source) } catch (error: java.io.IOException) { failure = error; null } ?: break");
|
|
1826
|
+
writer.line("val line = if (firstLine) received.removePrefix(\"\\uFEFF\") else received");
|
|
1827
|
+
writer.line("firstLine = false");
|
|
1828
|
+
writer.block("if (line.isEmpty())", () => {
|
|
1829
|
+
writer.line("lastEventId = pendingId");
|
|
1830
|
+
writer.block("if (dataLines.isNotEmpty())", () => {
|
|
1831
|
+
writer.line("emit(ServerSentEvent(eventType.ifEmpty { null }, dataLines.joinToString(\"\\n\"), lastEventId.ifEmpty { null }, retry))");
|
|
1832
|
+
writer.line("attempts = 0");
|
|
1833
|
+
writer.line("failure = null");
|
|
1834
|
+
writer.line("dataLines.clear()");
|
|
1835
|
+
writer.line("retry = null");
|
|
1836
|
+
});
|
|
1837
|
+
writer.line("eventType = \"\"");
|
|
1838
|
+
writer.line("continue");
|
|
1839
|
+
});
|
|
1840
|
+
writer.line("if (line.startsWith(\":\")) continue");
|
|
1841
|
+
writer.line("val separator = line.indexOf(':')");
|
|
1842
|
+
writer.line("val field = if (separator == -1) line else line.substring(0, separator)");
|
|
1843
|
+
writer.line("val value = (if (separator == -1) \"\" else line.substring(separator + 1)).removePrefix(\" \")");
|
|
1844
|
+
writer.block("when (field)", () => {
|
|
1845
|
+
writer.line("\"event\" -> eventType = value");
|
|
1846
|
+
writer.line("\"data\" -> dataLines.add(value)");
|
|
1847
|
+
writer.line("\"id\" -> if (!value.contains('\\u0000')) pendingId = value");
|
|
1848
|
+
writer.line("\"retry\" -> if (value.isNotEmpty() && value.all { character -> character in '0'..'9' }) value.toIntOrNull()?.let { milliseconds -> retry = milliseconds; reconnectionTime = minOf(milliseconds.milliseconds, 3_600_000.milliseconds) }");
|
|
1544
1849
|
});
|
|
1545
|
-
writer.line("eventType = \"\"");
|
|
1546
|
-
writer.line("continue");
|
|
1547
|
-
});
|
|
1548
|
-
writer.line("if (line.startsWith(\":\")) continue");
|
|
1549
|
-
writer.line("val separator = line.indexOf(':')");
|
|
1550
|
-
writer.line("val field = if (separator == -1) line else line.substring(0, separator)");
|
|
1551
|
-
writer.line("val value = (if (separator == -1) \"\" else line.substring(separator + 1)).removePrefix(\" \")");
|
|
1552
|
-
writer.block("when (field)", () => {
|
|
1553
|
-
writer.line("\"event\" -> eventType = value");
|
|
1554
|
-
writer.line("\"data\" -> dataLines.add(value)");
|
|
1555
|
-
writer.line("\"id\" -> if (!value.contains('\\u0000')) lastEventId = value");
|
|
1556
|
-
writer.line("\"retry\" -> if (value.isNotEmpty() && value.all { it.isDigit() }) retry = value.toIntOrNull()");
|
|
1557
1850
|
});
|
|
1558
1851
|
});
|
|
1852
|
+
writer.block("if (reconnect == null || attempts >= reconnect.policy.maximumAttempts)", () => {
|
|
1853
|
+
writer.line("failure?.let { throw it }");
|
|
1854
|
+
writer.line("return@flow");
|
|
1855
|
+
});
|
|
1856
|
+
writer.line("attempts += 1");
|
|
1857
|
+
writer.line("val ceiling = minOf(reconnect.policy.maximumDelay, reconnectionTime * Math.pow(2.0, (attempts - 1).toDouble()))");
|
|
1858
|
+
writer.line("val extra = (ceiling - reconnectionTime).coerceAtLeast(kotlin.time.Duration.ZERO)");
|
|
1859
|
+
writer.line("kotlinx.coroutines.delay(reconnectionTime + extra * Math.random())");
|
|
1860
|
+
writer.line("current = try { reconnect.reopen(lastEventId) ?: return@flow } catch (error: java.io.IOException) { failure = error; null }");
|
|
1559
1861
|
});
|
|
1560
1862
|
});
|
|
1561
1863
|
writer.blank();
|
|
1562
|
-
writer.line("fun <Event : Any> events(response: Response, decode: (ServerSentEvent) -> Event?): Flow<Event> = serverSentEvents(response).mapNotNull(decode)");
|
|
1864
|
+
writer.line("fun <Event : Any> events(response: Response, reconnect: Reconnection? = null, decode: (ServerSentEvent) -> Event?): Flow<Event> = serverSentEvents(response, reconnect).mapNotNull(decode)");
|
|
1563
1865
|
};
|
|
1564
1866
|
const emitKizunaObject = (writer, options) => {
|
|
1565
1867
|
writer.blank();
|
|
1566
1868
|
writer.block("private object Kizuna", () => {
|
|
1567
|
-
if (options.streaming) emitKizunaStreaming(writer);
|
|
1869
|
+
if (options.streaming) emitKizunaStreaming(writer, options.clientName);
|
|
1568
1870
|
writer.block("fun resolveUrl(baseUrl: String, path: String): HttpUrl.Builder", () => {
|
|
1569
1871
|
writer.line("val base = baseUrl.toHttpUrl()");
|
|
1570
1872
|
writer.line("val trimmedPath = path.trimStart('/')");
|
|
@@ -1578,18 +1880,76 @@ const emitKizunaObject = (writer, options) => {
|
|
|
1578
1880
|
writer.line("return java.net.URLEncoder.encode(text, \"UTF-8\").replace(\"+\", \"%20\")");
|
|
1579
1881
|
});
|
|
1580
1882
|
writer.blank();
|
|
1883
|
+
if (options.jsonQuery) {
|
|
1884
|
+
writer.line("// One JSON text with every object's keys in order so one value always gives one URL.");
|
|
1885
|
+
writer.block("inline fun <reified Value> encodeQueryJson(json: Json, value: Value): String", () => {
|
|
1886
|
+
writer.line("return sortJsonKeys(json.encodeToJsonElement(value)).toString()");
|
|
1887
|
+
});
|
|
1888
|
+
writer.blank();
|
|
1889
|
+
writer.block("fun sortJsonKeys(element: JsonElement): JsonElement", () => {
|
|
1890
|
+
writer.line("return when (element) {");
|
|
1891
|
+
writer.indent(() => {
|
|
1892
|
+
writer.line("is JsonObject -> JsonObject(element.toSortedMap().mapValues { sortJsonKeys(it.value) })");
|
|
1893
|
+
writer.line("is JsonArray -> JsonArray(element.map { sortJsonKeys(it) })");
|
|
1894
|
+
writer.line("else -> element");
|
|
1895
|
+
});
|
|
1896
|
+
writer.line("}");
|
|
1897
|
+
});
|
|
1898
|
+
writer.blank();
|
|
1899
|
+
}
|
|
1581
1900
|
writer.block("fun stringifyQueryValue(value: Any): List<String>", () => {
|
|
1582
1901
|
writer.line("return when (value) {");
|
|
1583
1902
|
writer.indent(() => {
|
|
1584
1903
|
writer.line("is Instant -> listOf(value.toString())");
|
|
1585
1904
|
writer.line("is List<*> -> value.filterNotNull().flatMap { stringifyQueryValue(it) }");
|
|
1586
|
-
writer.line("is KizunaQueryValue -> listOf(value.wireValue)");
|
|
1905
|
+
if (options.queryValues) writer.line("is KizunaQueryValue -> listOf(value.wireValue)");
|
|
1587
1906
|
writer.line("is Enum<*> -> listOf(value.name)");
|
|
1588
1907
|
writer.line("else -> listOf(value.toString())");
|
|
1589
1908
|
});
|
|
1590
1909
|
writer.line("}");
|
|
1591
1910
|
});
|
|
1592
1911
|
writer.blank();
|
|
1912
|
+
writer.block(`suspend fun send(client: OkHttpClient, request: Request, retry: ${options.clientName}.RetryPolicy?): Response`, () => {
|
|
1913
|
+
writer.line("val idempotent = request.method in setOf(\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\")");
|
|
1914
|
+
writer.line("val policy = retry?.takeIf { idempotent && request.body?.isOneShot() != true }");
|
|
1915
|
+
writer.line("var attempt = 1");
|
|
1916
|
+
writer.block("while (true)", () => {
|
|
1917
|
+
writer.line("val response = try {");
|
|
1918
|
+
writer.line(" execute(client, request)");
|
|
1919
|
+
writer.line("} catch (error: java.io.IOException) {");
|
|
1920
|
+
writer.line(" val delay = policy?.let { retryDelay(it, attempt, null) } ?: throw error");
|
|
1921
|
+
writer.line(" kotlinx.coroutines.delay(delay)");
|
|
1922
|
+
writer.line(" attempt += 1");
|
|
1923
|
+
writer.line(" continue");
|
|
1924
|
+
writer.line("}");
|
|
1925
|
+
writer.line("val delay = policy?.let { retryDelay(it, attempt, response) } ?: return response");
|
|
1926
|
+
writer.line("response.close()");
|
|
1927
|
+
writer.line("kotlinx.coroutines.delay(delay)");
|
|
1928
|
+
writer.line("attempt += 1");
|
|
1929
|
+
});
|
|
1930
|
+
});
|
|
1931
|
+
writer.blank();
|
|
1932
|
+
writer.block(`fun retryDelay(policy: ${options.clientName}.RetryPolicy, attempt: Int, response: Response?): Long?`, () => {
|
|
1933
|
+
writer.line("if (attempt >= policy.maximumAttempts) return null");
|
|
1934
|
+
writer.line("val ceiling = minOf(policy.maximumDelay.inWholeMilliseconds, policy.initialDelay.inWholeMilliseconds shl (attempt - 1))");
|
|
1935
|
+
writer.line("val backoff = (Math.random() * ceiling).toLong()");
|
|
1936
|
+
writer.line("if (response == null) return backoff");
|
|
1937
|
+
writer.line("if (response.code != 429 && response.code != 503) return null");
|
|
1938
|
+
writer.line("val asked = retryAfter(response.header(\"Retry-After\")) ?: return backoff");
|
|
1939
|
+
writer.line("return if (asked <= policy.maximumDelay.inWholeMilliseconds) asked else null");
|
|
1940
|
+
});
|
|
1941
|
+
writer.blank();
|
|
1942
|
+
writer.block("fun retryAfter(header: String?): Long?", () => {
|
|
1943
|
+
writer.line("val value = header?.trim() ?: return null");
|
|
1944
|
+
writer.line("value.toLongOrNull()?.let { return if (it >= 0) it * 1000 else null }");
|
|
1945
|
+
writer.line("val date = try {");
|
|
1946
|
+
writer.line(" java.time.ZonedDateTime.parse(value, java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME)");
|
|
1947
|
+
writer.line("} catch (_: java.time.format.DateTimeParseException) {");
|
|
1948
|
+
writer.line(" return null");
|
|
1949
|
+
writer.line("}");
|
|
1950
|
+
writer.line("return maxOf(0L, date.toInstant().toEpochMilli() - System.currentTimeMillis())");
|
|
1951
|
+
});
|
|
1952
|
+
writer.blank();
|
|
1593
1953
|
writer.block("suspend fun execute(client: OkHttpClient, request: Request): Response", () => {
|
|
1594
1954
|
writer.line("return kotlinx.coroutines.suspendCancellableCoroutine { continuation ->");
|
|
1595
1955
|
writer.indent(() => {
|
|
@@ -1617,20 +1977,48 @@ const emitClient = (writer, config, partition, context, typesByOperation, regist
|
|
|
1617
1977
|
const allMethods = [...flatMethods, ...groups.flatMap((group) => group.methods)];
|
|
1618
1978
|
const usesMultipart = allMethods.some((method) => method.body?.kind === "multipart");
|
|
1619
1979
|
const contextFields = context.requestContextFields;
|
|
1620
|
-
const contextRequired = contextFields.some((field) => !field
|
|
1980
|
+
const contextRequired = contextFields.some((field) => !hasDefault(field));
|
|
1621
1981
|
const contextParam = contextFields.length > 0 ? `requestContext: RequestContext${contextRequired ? "" : " = RequestContext()"}, ` : "";
|
|
1622
1982
|
writer.blank();
|
|
1623
|
-
writer.block(`class ${clientName}(private val baseUrl: String, ${contextParam}private val client: OkHttpClient = OkHttpClient(), private val json: Json = Json { ignoreUnknownKeys = true }, private val requestInterceptor: (suspend (Request.Builder) -> Unit)? = null, private val responseInterceptor: (suspend (Request, Response) -> Unit)? = null)`, () => {
|
|
1983
|
+
writer.block(`class ${clientName}(private val baseUrl: String, ${contextParam}private val client: OkHttpClient = OkHttpClient(), private val json: Json = Json { ignoreUnknownKeys = true }, private val requestInterceptor: (suspend (Request.Builder) -> Unit)? = null, private val responseInterceptor: (suspend (Request, Response) -> Unit)? = null, private val retry: RetryPolicy? = null, private val reconnect: ReconnectPolicy? = null)`, () => {
|
|
1624
1984
|
if (contextFields.length > 0) {
|
|
1625
1985
|
writer.blank();
|
|
1626
1986
|
writer.line("/** Values sent as headers on every request, from the api's request context. */");
|
|
1627
|
-
emitConstructorClass(writer, "data class RequestContext", contextFields.map((field) => `val ${escapeKeyword(field.name)}: ${field.type}${field
|
|
1987
|
+
emitConstructorClass(writer, "data class RequestContext", contextFields.map((field) => `val ${escapeKeyword(field.name)}: ${field.type}${defaultArgument(field)}`));
|
|
1628
1988
|
writer.blank();
|
|
1629
1989
|
writer.block("private val requestContextHeaders: Map<String, String> = buildMap", () => {
|
|
1630
1990
|
for (const field of contextFields) if (field.optional) writer.line(`if (requestContext.${escapeKeyword(field.name)} != null) put(${stringLiteral(field.wireName)}, requestContext.${escapeKeyword(field.name)}!!)`);
|
|
1631
1991
|
else writer.line(`put(${stringLiteral(field.wireName)}, requestContext.${escapeKeyword(field.name)})`);
|
|
1632
1992
|
});
|
|
1633
1993
|
}
|
|
1994
|
+
writer.blank();
|
|
1995
|
+
writer.line("/**");
|
|
1996
|
+
writer.line(" * Retries a GET, HEAD, OPTIONS, PUT or DELETE that failed on the network or was answered 429 or 503,");
|
|
1997
|
+
writer.line(" * waiting what Retry-After asks or backing off.");
|
|
1998
|
+
writer.line(" *");
|
|
1999
|
+
writer.line(" * @property maximumAttempts Attempts in all, the first included.");
|
|
2000
|
+
writer.line(" * @property initialDelay What the first backoff waits at most.");
|
|
2001
|
+
writer.line(" * @property maximumDelay What any wait may take.");
|
|
2002
|
+
writer.line(" */");
|
|
2003
|
+
emitConstructorClass(writer, "data class RetryPolicy", [
|
|
2004
|
+
"val maximumAttempts: Int = 3",
|
|
2005
|
+
"val initialDelay: kotlin.time.Duration = 500.milliseconds",
|
|
2006
|
+
"val maximumDelay: kotlin.time.Duration = 30.seconds"
|
|
2007
|
+
]);
|
|
2008
|
+
writer.blank();
|
|
2009
|
+
writer.line("/**");
|
|
2010
|
+
writer.line(" * Reconnects an event stream on a GET, HEAD, OPTIONS, PUT or DELETE when its connection drops,");
|
|
2011
|
+
writer.line(" * sending the id of the last event as Last-Event-ID.");
|
|
2012
|
+
writer.line(" *");
|
|
2013
|
+
writer.line(" * @property maximumAttempts Reconnections in a row before the stream fails. An event received resets the count.");
|
|
2014
|
+
writer.line(" * @property reconnectionTime What to wait before reconnecting, until the server sends a retry field.");
|
|
2015
|
+
writer.line(" * @property maximumDelay What the wait may grow to after reconnections in a row that fail.");
|
|
2016
|
+
writer.line(" */");
|
|
2017
|
+
emitConstructorClass(writer, "data class ReconnectPolicy", [
|
|
2018
|
+
"val maximumAttempts: Int = 5",
|
|
2019
|
+
"val reconnectionTime: kotlin.time.Duration = 3.seconds",
|
|
2020
|
+
"val maximumDelay: kotlin.time.Duration = 30.seconds"
|
|
2021
|
+
]);
|
|
1634
2022
|
if (usesMultipart) {
|
|
1635
2023
|
writer.blank();
|
|
1636
2024
|
emitConstructorClass(writer, "data class MultipartFile", [
|
|
@@ -1686,7 +2074,7 @@ const emitClient = (writer, config, partition, context, typesByOperation, regist
|
|
|
1686
2074
|
}
|
|
1687
2075
|
if (groups.length > 0) for (const group of groups) {
|
|
1688
2076
|
writer.blank();
|
|
1689
|
-
writer.line(`val ${escapeKeyword(group.propertyName)} = ${group.className}(client, baseUrl, json, ${contextFields.length > 0 ? "requestContextHeaders" : "emptyMap()"}, requestInterceptor, responseInterceptor)`);
|
|
2077
|
+
writer.line(`val ${escapeKeyword(group.propertyName)} = ${group.className}(client, baseUrl, json, ${contextFields.length > 0 ? "requestContextHeaders" : "emptyMap()"}, requestInterceptor, responseInterceptor, retry, reconnect)`);
|
|
1690
2078
|
}
|
|
1691
2079
|
for (const method of flatMethods) {
|
|
1692
2080
|
writer.blank();
|
|
@@ -1694,21 +2082,8 @@ const emitClient = (writer, config, partition, context, typesByOperation, regist
|
|
|
1694
2082
|
}
|
|
1695
2083
|
});
|
|
1696
2084
|
};
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
*
|
|
1700
|
-
* @param api - What `defineConfig` assembled.
|
|
1701
|
-
* @param config - Override the generated names:
|
|
1702
|
-
* - `namespaceName`: the object wrapping shared types.
|
|
1703
|
-
* - `packageName`: optional package declaration for the generated file.
|
|
1704
|
-
*/
|
|
1705
|
-
const generateKotlinClient = (api, config) => {
|
|
1706
|
-
const { namespaceName, packageName, camelCaseProperties = false, unknownEnumCase = false } = config;
|
|
1707
|
-
const registry = new TypeRegistry(camelCaseProperties, unknownEnumCase);
|
|
1708
|
-
const partition = kotlinGenerator(api, {
|
|
1709
|
-
namespaceName,
|
|
1710
|
-
registry
|
|
1711
|
-
});
|
|
2085
|
+
const renderKotlinClient = (api, partition, registry, config) => {
|
|
2086
|
+
const { namespaceName, packageName, camelCaseProperties = false } = config;
|
|
1712
2087
|
const allMethods = [...partition.flatMethods, ...partition.groups.flatMap((group) => group.methods)];
|
|
1713
2088
|
const operationTypeMap = buildOperationTypeMap(allMethods, registry);
|
|
1714
2089
|
const clientName = `${namespaceName}Client`;
|
|
@@ -1734,19 +2109,23 @@ const generateKotlinClient = (api, config) => {
|
|
|
1734
2109
|
}
|
|
1735
2110
|
writer.line("import kotlinx.serialization.*");
|
|
1736
2111
|
writer.line("import kotlinx.serialization.json.*");
|
|
1737
|
-
if (registry.all().some((type) => type.kind === "enum-class" && type.unknownCase)) {
|
|
2112
|
+
if (registry.all().some((type) => (type.kind === "enum-class" || type.kind === "sealed-class") && type.unknownCase)) {
|
|
1738
2113
|
writer.line("import kotlinx.serialization.descriptors.*");
|
|
1739
2114
|
writer.line("import kotlinx.serialization.encoding.*");
|
|
1740
2115
|
}
|
|
1741
2116
|
writer.line("import kotlinx.datetime.Instant");
|
|
1742
2117
|
const usesStreaming = allMethods.some((method) => method.stream !== void 0);
|
|
2118
|
+
const sendsJsonQuery = allMethods.some((method) => method.query.some((field) => field.json));
|
|
1743
2119
|
if (usesStreaming) writer.line("import kotlinx.coroutines.flow.*");
|
|
1744
2120
|
writer.line("import okhttp3.*");
|
|
1745
2121
|
writer.line("import okhttp3.MediaType.Companion.toMediaType");
|
|
1746
2122
|
writer.line("import okhttp3.RequestBody.Companion.toRequestBody");
|
|
2123
|
+
writer.line("import kotlin.time.Duration.Companion.milliseconds");
|
|
2124
|
+
writer.line("import kotlin.time.Duration.Companion.seconds");
|
|
1747
2125
|
writer.line("import okhttp3.HttpUrl.Companion.toHttpUrl");
|
|
1748
2126
|
writer.blank();
|
|
1749
|
-
|
|
2127
|
+
const hasEnums = registry.all().some((type) => type.kind === "enum-class");
|
|
2128
|
+
if (hasEnums) {
|
|
1750
2129
|
writer.block("interface KizunaQueryValue", () => {
|
|
1751
2130
|
writer.line("val wireValue: String");
|
|
1752
2131
|
});
|
|
@@ -1783,23 +2162,61 @@ const generateKotlinClient = (api, config) => {
|
|
|
1783
2162
|
if (!headersSchema) continue;
|
|
1784
2163
|
requestContextFields.push(...collectObjectFields(headersSchema, registry, "RequestContext"));
|
|
1785
2164
|
}
|
|
2165
|
+
const builderModelNames = new Set(sharedTypes.filter(isBuilderModel).map((type) => type.name));
|
|
1786
2166
|
const context = {
|
|
1787
2167
|
namespaceName,
|
|
1788
2168
|
clientName,
|
|
1789
2169
|
operationTypeMap,
|
|
1790
2170
|
fileLevelTypeNames,
|
|
1791
2171
|
ownedTypeMap,
|
|
1792
|
-
requestContextFields
|
|
2172
|
+
requestContextFields,
|
|
2173
|
+
builderModelNames
|
|
1793
2174
|
};
|
|
1794
2175
|
writer.block(`object ${namespaceName}`, () => {
|
|
1795
|
-
|
|
2176
|
+
if (builderModelNames.size > 0) {
|
|
2177
|
+
writer.line("@DslMarker");
|
|
2178
|
+
writer.line("annotation class KizunaDsl");
|
|
2179
|
+
}
|
|
2180
|
+
emitTypes(writer, topLevelSharedTypes, ownedTypeMap, ownedTypeLookup, registry, builderModelNames.size > 0);
|
|
2181
|
+
for (const brand of registry.allBrands()) {
|
|
2182
|
+
writer.blank();
|
|
2183
|
+
emitBrand(writer, brand);
|
|
2184
|
+
}
|
|
1796
2185
|
});
|
|
1797
2186
|
emitClient(writer, { clientName }, partition, context, typesByOperation, registry);
|
|
1798
2187
|
for (const group of partition.groups) emitSubClientClass(writer, group, clientName, context);
|
|
1799
|
-
emitKizunaObject(writer, {
|
|
2188
|
+
emitKizunaObject(writer, {
|
|
2189
|
+
streaming: usesStreaming,
|
|
2190
|
+
queryValues: hasEnums,
|
|
2191
|
+
jsonQuery: sendsJsonQuery,
|
|
2192
|
+
clientName
|
|
2193
|
+
});
|
|
1800
2194
|
for (const warning of registry.warnings()) process.stderr.write(`[kizuna/kotlin] JsonElement fallback at ${warning}\n`);
|
|
1801
2195
|
return writer.toString();
|
|
1802
2196
|
};
|
|
2197
|
+
/**
|
|
2198
|
+
* The Kotlin client's walk: the routes into a partition, then the file.
|
|
2199
|
+
*/
|
|
2200
|
+
const kotlinClientWalk = (api, config) => {
|
|
2201
|
+
const registry = new TypeRegistry(config.camelCaseProperties ?? false, config.unknownEnumCase ?? false);
|
|
2202
|
+
const routes = kotlinRoutesWalk({
|
|
2203
|
+
namespaceName: config.namespaceName,
|
|
2204
|
+
registry
|
|
2205
|
+
});
|
|
2206
|
+
return {
|
|
2207
|
+
processRoute: routes.processRoute,
|
|
2208
|
+
finalize: () => renderKotlinClient(api, routes.finalize(), registry, config)
|
|
2209
|
+
};
|
|
2210
|
+
};
|
|
2211
|
+
/**
|
|
2212
|
+
* Generate a Kotlin API client from a Kizuna api.
|
|
2213
|
+
*
|
|
2214
|
+
* @param api - What `defineConfig` assembled.
|
|
2215
|
+
* @param config - Override the generated names:
|
|
2216
|
+
* - `namespaceName`: the object wrapping shared types.
|
|
2217
|
+
* - `packageName`: optional package declaration for the generated file.
|
|
2218
|
+
*/
|
|
2219
|
+
const generateKotlinClient = (api, config) => (0, kizunajs_generator.walkApi)(api, kotlinClientWalk(api, config), { skipHidden: true });
|
|
1803
2220
|
//#endregion
|
|
1804
2221
|
Object.defineProperty(exports, "generateKotlinClient", {
|
|
1805
2222
|
enumerable: true,
|
|
@@ -1807,3 +2224,9 @@ Object.defineProperty(exports, "generateKotlinClient", {
|
|
|
1807
2224
|
return generateKotlinClient;
|
|
1808
2225
|
}
|
|
1809
2226
|
});
|
|
2227
|
+
Object.defineProperty(exports, "kotlinClientWalk", {
|
|
2228
|
+
enumerable: true,
|
|
2229
|
+
get: function() {
|
|
2230
|
+
return kotlinClientWalk;
|
|
2231
|
+
}
|
|
2232
|
+
});
|