Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ public class DartDioClientCodegen extends AbstractDartCodegen {
public static final String SKIP_COPY_WITH_DEFAULT_VALUE = "false";

private static final String CLIENT_NAME = "clientName";
private static final String X_DISCRIMINATOR_MAPPED_MODELS_NONSELF = "x-discriminator-mapped-models-nonself";
private static final String X_HAS_DISCRIMINATOR_SELF_MAPPING = "x-has-discriminator-self-mapping";
private static final String X_DISCRIMINATOR_SELF_MAPPING_NAME = "x-discriminator-self-mapping-name";

@Getter @Setter
private String dateLibrary;
Expand Down Expand Up @@ -293,6 +296,7 @@ private void configureSerializationLibraryBuiltValue(String srcFolder) {

private void configureSerializationLibraryJsonSerializable(String srcFolder) {
supportingFiles.add(new SupportingFile("serialization/json_serializable/build.yaml.mustache", "" /* main project dir */, "build.yaml"));
supportingFiles.add(new SupportingFile("serialization/json_serializable/api_util.mustache", srcFolder, "api_util.dart"));
supportingFiles.add(new SupportingFile("serialization/json_serializable/deserialize.mustache", srcFolder,
"deserialize.dart"));

Expand Down Expand Up @@ -583,36 +587,278 @@ private void adaptToDartInheritance(Map<String, ModelsMap> objs) {
}
}

/// override the default behavior of createDiscriminator
/// to remove extra mappings added as a side effect of setLegacyDiscriminatorBehavior(false)
/// this ensures 1-1 schema mapping instead of 1-many
/**
* Computes the maximum allOf inheritance distance from {@code schemaName} to
* {@code ancestorSchemaName}.
*
* <p>Returns {@code 0} when both schema names are equal, and {@code -1} when no
* inheritance path exists. The {@code visited} set prevents infinite recursion on
* cyclic graphs.
*/
private int getSchemaInheritanceDepth(String schemaName, String ancestorSchemaName, Set<String> visited) {

@wing328 wing328 May 21, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: what about adding docstrings explaining what this function and other newly added functions do?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wing328 I did add some comments and also fixed another issue in regards to a possible null cast
Could you take another look?

if (schemaName == null || ancestorSchemaName == null) {
return -1;
}
if (schemaName.equals(ancestorSchemaName)) {
return 0;
}

Schema currentSchema = ModelUtils.getSchema(openAPI, schemaName);
if (currentSchema == null || currentSchema.getAllOf() == null || currentSchema.getAllOf().isEmpty()) {
return -1;
}

int maxDepth = -1;
for (Object parentObj : currentSchema.getAllOf()) {
if (!(parentObj instanceof Schema)) {
continue;
}
Schema parentSchema = (Schema) parentObj;
String parentRef = parentSchema.get$ref();
if (parentRef == null) {
continue;
}

String parentSchemaName = ModelUtils.getSimpleRef(parentRef);
if (ancestorSchemaName.equals(parentSchemaName)) {
maxDepth = Math.max(maxDepth, 1);
continue;
}

if (parentSchemaName != null && visited.add(parentSchemaName)) {
int parentDepth = getSchemaInheritanceDepth(parentSchemaName, ancestorSchemaName, visited);
if (parentDepth >= 0) {
maxDepth = Math.max(maxDepth, parentDepth + 1);
}
visited.remove(parentSchemaName);
}
}

return maxDepth;
}

/**
* Builds discriminator metadata and removes implicit/over-broad mappings so Dart
* generation keeps a strict one-schema-per-discriminator-entry behavior.
*
* <p>For schema-local discriminators, only explicitly declared mappings are kept.
* For inherited discriminators, mappings are restricted to true allOf descendants
* of the current schema.
*/
@Override
protected CodegenDiscriminator createDiscriminator(String schemaName, Schema schema) {
CodegenDiscriminator sub = super.createDiscriminator(schemaName, schema);
Discriminator originalDiscriminator = schema.getDiscriminator();
if (sub == null) {
return null;
}

if (sub.getMapping() != null) {
// Defensive copy: avoid mutating shared mapping objects from the parsed spec.
sub.setMapping(new LinkedHashMap<>(sub.getMapping()));
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
}
sub.setVendorExtensions(new LinkedHashMap<>(ObjectUtils.firstNonNull(sub.getVendorExtensions(), Collections.emptyMap())));

Discriminator originalDiscriminator = getSchemaLocalDiscriminator(schema);
if (originalDiscriminator != null) {
Map<String, String> originalMapping = originalDiscriminator.getMapping();
if (originalMapping != null && !originalMapping.isEmpty()) {
//we already have a discriminator mapping, remove everything else
for (MappedModel currentMappings : new HashSet<>(sub.getMappedModels())) {
if (originalMapping.containsKey(currentMappings.getMappingName())) {
//all good
} else {
sub.getMapping().remove(currentMappings.getMappingName());
sub.getMappedModels().remove(currentMappings);
}
}
// keep only explicitly declared mappings on the schema-local discriminator
filterMappedModels(sub, mappedModel -> originalMapping.containsKey(mappedModel.getMappingName()));
}
orderMappedModelsBySchemaSpecificity(sub, schemaName);
prepareDiscriminatorTemplateData(sub, schemaName, toModelName(schemaName));
return sub;
}

// For inherited discriminators, keep real allOf descendants of this schema
// (e.g. Reptile keeps Crocodile/Turtle, but not Bird from Animal's mapping).
// Also preserve alternatives declared directly in this schema's oneOf/anyOf.
Set<String> descendantSchemaNames = getAllOfDescendants(schemaName).stream()
.map(MappedModel::getSchemaName)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Set<String> declaredAlternatives = getComposedAlternativeSchemaNames(schema);

if (ModelUtils.isComposedSchema(schema) && schema.getAllOf() != null) {
filterMappedModels(sub, mappedModel -> descendantSchemaNames.contains(mappedModel.getSchemaName())
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
|| declaredAlternatives.contains(mappedModel.getSchemaName())
|| schemaName.equals(mappedModel.getSchemaName()));
}

orderMappedModelsBySchemaSpecificity(sub, schemaName);
prepareDiscriminatorTemplateData(sub, schemaName, toModelName(schemaName));
return sub;
}

/**
* Prepares discriminator vendor extensions consumed by Dart templates.
*
* <p>The method separates non-self mapped models and records whether the
* discriminator includes a self-mapping plus its mapping key.
*/
private void prepareDiscriminatorTemplateData(CodegenDiscriminator discriminator, String schemaName, String modelName) {
if (discriminator == null || discriminator.getMappedModels() == null) {
return;
}

String selfMappingName = null;
List<MappedModel> nonSelfMappedModels = new ArrayList<>();
for (MappedModel mappedModel : discriminator.getMappedModels()) {
boolean isSelfMapping = Objects.equals(schemaName, mappedModel.getSchemaName())
|| Objects.equals(modelName, mappedModel.getModelName());
if (isSelfMapping) {
selfMappingName = mappedModel.getMappingName();
} else {
nonSelfMappedModels.add(mappedModel);
}
}

Map<String, Object> discriminatorVendorExtensions = discriminator.getVendorExtensions();
if (discriminatorVendorExtensions == null) {
discriminatorVendorExtensions = new LinkedHashMap<>();
discriminator.setVendorExtensions(discriminatorVendorExtensions);
}

discriminatorVendorExtensions.put(X_DISCRIMINATOR_MAPPED_MODELS_NONSELF, nonSelfMappedModels);
discriminatorVendorExtensions.put(X_HAS_DISCRIMINATOR_SELF_MAPPING, selfMappingName != null);
if (selfMappingName != null) {
discriminatorVendorExtensions.put(X_DISCRIMINATOR_SELF_MAPPING_NAME, selfMappingName);
} else {
discriminatorVendorExtensions.remove(X_DISCRIMINATOR_SELF_MAPPING_NAME);
}
}

/**
* Orders discriminator mapped models by schema specificity relative to the owner
* schema (deepest descendants first).
*
* <p>When two mappings have the same depth, the original insertion order is
* preserved for deterministic output.
*/
private void orderMappedModelsBySchemaSpecificity(CodegenDiscriminator discriminator, String ownerSchemaName) {
if (discriminator.getMappedModels() == null || discriminator.getMappedModels().size() < 2) {
return;
}

List<MappedModel> ordered = new ArrayList<>(discriminator.getMappedModels());
Map<String, Integer> inheritanceDepthBySchema = new HashMap<>();
Map<MappedModel, Integer> originalOrder = new HashMap<>();
for (int i = 0; i < ordered.size(); i++) {
MappedModel mappedModel = ordered.get(i);
originalOrder.put(mappedModel, i);
inheritanceDepthBySchema.computeIfAbsent(
mappedModel.getSchemaName(),
schemaName -> getSchemaInheritanceDepth(schemaName, ownerSchemaName, new HashSet<>())
);
}

ordered.sort((left, right) -> {
int leftDepth = inheritanceDepthBySchema.getOrDefault(left.getSchemaName(), -1);
int rightDepth = inheritanceDepthBySchema.getOrDefault(right.getSchemaName(), -1);
if (leftDepth != rightDepth) {
return Integer.compare(rightDepth, leftDepth);
}

return Integer.compare(originalOrder.get(left), originalOrder.get(right));
});

discriminator.setMappedModels(new LinkedHashSet<>(ordered));
}

/**
* Removes discriminator mapped models that do not satisfy the provided predicate.
*
* <p>Both the mapped model set and the optional mapping-name lookup map are kept
* in sync.
*/
private void filterMappedModels(CodegenDiscriminator discriminator, java.util.function.Predicate<MappedModel> keepPredicate) {
for (MappedModel mappedModel : new HashSet<>(discriminator.getMappedModels())) {
if (!keepPredicate.test(mappedModel)) {
if (discriminator.getMapping() != null) {
discriminator.getMapping().remove(mappedModel.getMappingName());
}
discriminator.getMappedModels().remove(mappedModel);
}
}
}

/**
* Returns the discriminator defined on the schema itself, including an inline
* allOf segment, but excluding discriminators inherited from parent schemas.
*/
private Discriminator getSchemaLocalDiscriminator(Schema schema) {
if (schema == null) {
return null;
}

if (schema.getDiscriminator() != null) {
return schema.getDiscriminator();
}

if (ModelUtils.isComposedSchema(schema) && schema.getAllOf() != null) {
// Prefer inline allOf discriminator (child-local) over inherited parent discriminators.
for (Object allOfSchemaObj : schema.getAllOf()) {
if (!(allOfSchemaObj instanceof Schema)) {
continue;
}
Schema allOfSchema = (Schema) allOfSchemaObj;
if (allOfSchema.getDiscriminator() != null) {
return allOfSchema.getDiscriminator();
}
}
}

return null;
}

/**
* Gets schema names referenced directly by oneOf/anyOf in the provided schema.
*/
private Set<String> getComposedAlternativeSchemaNames(Schema schema) {
Set<String> alternatives = new HashSet<>();
if (schema == null || !ModelUtils.isComposedSchema(schema)) {
return alternatives;
}

List<Schema> oneOfSchemas = schema.getOneOf();
if (oneOfSchemas != null) {
for (Schema oneOfSchema : oneOfSchemas) {
String ref = oneOfSchema != null ? oneOfSchema.get$ref() : null;
if (ref != null) {
alternatives.add(ModelUtils.getSimpleRef(ref));
}
}
}

List<Schema> anyOfSchemas = schema.getAnyOf();
if (anyOfSchemas != null) {
for (Schema anyOfSchema : anyOfSchemas) {
String ref = anyOfSchema != null ? anyOfSchema.get$ref() : null;
if (ref != null) {
alternatives.add(ModelUtils.getSimpleRef(ref));
}
}
}

return alternatives;
}

@Override
public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs) {
objs = super.postProcessAllModels(objs);
if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) {
adaptToDartInheritance(objs);
syncRootTypesWithInnerVars(objs);
for (ModelsMap entry : objs.values()) {
for (ModelMap mo : entry.getModels()) {
CodegenModel cm = mo.getModel();
if (cm != null && cm.discriminator != null) {
String ownerSchemaName = ObjectUtils.firstNonNull(cm.getSchemaName(), cm.getName(), cm.getClassname());
orderMappedModelsBySchemaSpecificity(cm.discriminator, ownerSchemaName);
prepareDiscriminatorTemplateData(cm.discriminator, cm.getSchemaName(), cm.classname);
}
}
}
}

// loop through models to update the imports
Expand Down Expand Up @@ -875,7 +1121,8 @@ private void processImports(List<CodegenOperation> operationList, java.util.func
}
}

if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library) && (op.getHasFormParams() || op.getHasQueryParams() || op.getHasPathParams())) {
if ((SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library) || SERIALIZATION_LIBRARY_JSON_SERIALIZABLE.equals(library))
&& (op.getHasFormParams() || op.getHasQueryParams() || op.getHasPathParams())) {
resultImports.add("package:" + pubName + "/" + sourceFolder + "/api_util.dart");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class {{classname}} {
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
final _path = r'{{{path}}}'{{#pathParams}}.replaceAll('{' r'{{{baseName}}}' '}', {{#includeLibraryTemplate}}api/query_param{{/includeLibraryTemplate}}.toString()){{/pathParams}};
final _path = r'{{{path}}}'{{#pathParams}}.replaceAll('{' r'{{{baseName}}}' '}', {{#includeLibraryTemplate}}api/path_param{{/includeLibraryTemplate}}){{/pathParams}};
final _options = Options(
method: r'{{#lambda.uppercase}}{{httpMethod}}{{/lambda.uppercase}}',
{{#isResponseFile}}
Expand Down Expand Up @@ -86,7 +86,14 @@ class {{classname}} {
{{#queryParams}}
{{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{baseName}}': {{#includeLibraryTemplate}}api/query_param{{/includeLibraryTemplate}},
{{/queryParams}}
};{{/hasQueryParams}}{{#hasBodyOrFormParams}}
};
removeNullQueryParametersExcept(
_queryParameters,
<String>{
{{#queryParams}}{{#required}}{{#isNullable}}r'{{baseName}}',
{{/isNullable}}{{/required}}{{/queryParams}}
},
);{{/hasQueryParams}}{{#hasBodyOrFormParams}}

dynamic _bodyData;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{#isContainer}}{{#isMap}}encodeFormParameter{{/isMap}}{{^isMap}}encodeCollectionFormParameter<{{{baseType}}}>{{/isMap}}{{/isContainer}}{{^isContainer}}encodeFormParameter{{/isContainer}}(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{dataType}}}){{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]), {{#collectionFormat}}format: ListFormat.{{collectionFormat}},{{/collectionFormat}}{{/isContainer}})
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{#isNullable}}{{{paramName}}} == null ? '' : {{{paramName}}}.toString(){{/isNullable}}{{^isNullable}}{{{paramName}}}.toString(){{/isNullable}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: For path parameters whose type is a collection (array/set), this template now emits paramName.toString(), which renders a Dart list literal such as [1, 2, 3] and leaves it unencoded in the URL. The replaced query_param/encodeCollectionQueryParameter path produced a comma-style (ListFormat) value. Path params support arrays per the OpenAPI spec, so either keep serialization for container types or emit style simple (comma-joined) values here.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/api/path_param.mustache, line 1:

<comment>For path parameters whose type is a collection (array/set), this template now emits `paramName.toString()`, which renders a Dart list literal such as `[1, 2, 3]` and leaves it unencoded in the URL. The replaced query_param/encodeCollectionQueryParameter path produced a comma-style (ListFormat) value. Path params support arrays per the OpenAPI spec, so either keep serialization for container types or emit style `simple` (comma-joined) values here.</comment>

<file context>
@@ -1 +1 @@
-({{>serialization/built_value/api/query_param}}{{#isNullable}}?.toString() ?? ''{{/isNullable}}{{^isNullable}}.toString(){{/isNullable}})
+{{#isNullable}}{{{paramName}}} == null ? '' : {{{paramName}}}.toString(){{/isNullable}}{{^isNullable}}{{{paramName}}}.toString(){{/isNullable}}
\ No newline at end of file
</file context>

Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
{{^isMultipart}}
_bodyData = <String, dynamic>{
{{#formParams}}
{{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{>serialization/built_value/api/query_param}},
{{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{>serialization/built_value/api/form_param}},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: For non-multipart forms with array (container) form params, form_param.mustache renders a call to encodeCollectionFormParameter<T>(...), but api_util.mustache only defines encodeCollectionQueryParameter. The regenerated sample confirms it: fake_api.dart calls encodeCollectionFormParameter<String> while api_util.dart never declares it, so the generated Dart won't compile for this case. Add encodeCollectionFormParameter to api_util.dart (mirroring encodeCollectionQueryParameter but returning form-encoded values), or keep the query_param partial here for collection params.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/api/serialize.mustache, line 12:

<comment>For non-multipart forms with array (container) form params, form_param.mustache renders a call to `encodeCollectionFormParameter<T>(...)`, but api_util.mustache only defines `encodeCollectionQueryParameter`. The regenerated sample confirms it: `fake_api.dart` calls `encodeCollectionFormParameter<String>` while `api_util.dart` never declares it, so the generated Dart won't compile for this case. Add `encodeCollectionFormParameter` to api_util.dart (mirroring `encodeCollectionQueryParameter` but returning form-encoded values), or keep the query_param partial here for collection params.</comment>

<file context>
@@ -9,7 +9,7 @@
       _bodyData = <String, dynamic>{
         {{#formParams}}
-        {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{>serialization/built_value/api/query_param}},
+        {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{>serialization/built_value/api/form_param}},
         {{/formParams}}
       };
</file context>

{{/formParams}}
};
{{/isMultipart}}
Expand Down
Loading