@arrirpc/codegen-dart 0.84.1 → 0.86.0

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.
Files changed (3) hide show
  1. package/dist/index.cjs +248 -23
  2. package/dist/index.mjs +249 -24
  3. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -303,7 +303,7 @@ function dartClassFromSchema(schema, context) {
303
303
  const toUrlQueryParts = [];
304
304
  if (context.discriminatorKey && context.discriminatorValue) {
305
305
  toUrlQueryParts.push(
306
- `_queryParts_.add("${context.discriminatorKey}=$${validDartIdentifier(context.discriminatorKey)}");`
306
+ `_queryParts_.add("${encodeURIComponent(context.discriminatorKey)}=${encodeURIComponent(context.discriminatorValue)}");`
307
307
  );
308
308
  }
309
309
  const copyWithParamParts = [];
@@ -336,7 +336,7 @@ function dartClassFromSchema(schema, context) {
336
336
  ` "${key}": ${typeResult.toJson(propName, "", key)},`
337
337
  );
338
338
  toUrlQueryParts.push(
339
- ` ${typeResult.toQueryString(propName, "_queryParts_", key)};`
339
+ ` ${typeResult.toQueryString(propName, "_queryParts_", encodeURIComponent(key))};`
340
340
  );
341
341
  if (typeResult.isNullable) {
342
342
  copyWithParamParts.push(
@@ -381,7 +381,7 @@ function dartClassFromSchema(schema, context) {
381
381
  ` if (${propName} != null) _output_["${key}"] = ${typeResult.toJson(propName, "_output_", key)};`
382
382
  );
383
383
  toUrlQueryParts.push(
384
- ` ${typeResult.toQueryString(propName, "_queryParts_", key)};`
384
+ ` ${typeResult.toQueryString(propName, "_queryParts_", encodeURIComponent(key))};`
385
385
  );
386
386
  copyWithParamParts.push(
387
387
  ` ${typeResult.typeName} Function()? ${propName},`
@@ -479,24 +479,43 @@ ${subContentParts.join("\n\n")}`;
479
479
  return result;
480
480
  }
481
481
 
482
- function dartSealedClassFromSchema(schema, context) {
482
+ function dartUnionFromSchema(schema, context) {
483
+ if (schema.tagKey && !schema.valueKey) {
484
+ for (const key of Object.keys(schema.union)) {
485
+ if (!codegenUtils.isSchemaFormProperties(schema.union[key])) {
486
+ throw new Error(
487
+ `Error at ${context.schemaPath}/union/${key}: All union variants must be an object when tagKey is specified without a valueKey`
488
+ );
489
+ }
490
+ }
491
+ return dartInternallyTaggedSealedClass(
492
+ schema,
493
+ schema.tagKey,
494
+ schema.union,
495
+ "union",
496
+ context
497
+ );
498
+ }
499
+ return dartWrappedUnionFromSchema(schema, context);
500
+ }
501
+ function dartInternallyTaggedSealedClass(schema, tagKey, variants, variantsSchemaKey, context) {
483
502
  const isNullable = outputIsNullable(schema, context);
484
503
  const className = getDartClassName(schema, context);
485
504
  const finalClassName = `${context.modelPrefix}${className}`;
486
505
  const typeName = isNullable ? `${finalClassName}?` : finalClassName;
487
506
  const defaultValue = isNullable ? `null` : `${finalClassName}.empty()`;
488
- const discriminatorKey = schema.discriminator;
507
+ const discriminatorKey = tagKey;
489
508
  const subTypeParts = [];
490
509
  const subContentParts = [];
491
- for (const key of Object.keys(schema.mapping)) {
492
- const subSchema = schema.mapping[key];
510
+ for (const key of Object.keys(variants)) {
511
+ const subSchema = variants[key];
493
512
  const discriminatorValue = key;
494
513
  const subTypeResult = dartClassFromSchema(subSchema, {
495
514
  clientName: context.clientName,
496
515
  modelPrefix: context.modelPrefix,
497
516
  generatedTypes: context.generatedTypes,
498
517
  instancePath: context.instancePath,
499
- schemaPath: `${context.schemaPath}/mapping/${key}`,
518
+ schemaPath: `${context.schemaPath}/${variantsSchemaKey}/${key}`,
500
519
  discriminatorKey,
501
520
  discriminatorValue,
502
521
  discriminatorParentId: className,
@@ -531,24 +550,28 @@ function dartSealedClassFromSchema(schema, context) {
531
550
  },
532
551
  toQueryString() {
533
552
  return `print(
534
- "[WARNING] nested objects cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
553
+ "[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
535
554
  },
536
555
  content: ""
537
556
  };
538
557
  if (context.generatedTypes.includes(className)) {
539
558
  return result;
540
559
  }
541
- const discriminatorProp = validDartIdentifier(schema.discriminator);
560
+ const fallbackKey = codegenUtils.getUnionFallbackKey(variants);
561
+ const fallbackType = subTypeParts.find(
562
+ (type) => type.value === fallbackKey
563
+ );
564
+ const discriminatorProp = validDartIdentifier(tagKey);
542
565
  result.content = `sealed class ${finalClassName} implements ArriModel {
543
566
  String get ${discriminatorProp};
544
567
  const ${finalClassName}();
545
568
 
546
569
  factory ${finalClassName}.empty() {
547
- return ${subTypeParts[0]?.name}.empty();
570
+ return ${fallbackType?.name}.empty();
548
571
  }
549
572
 
550
573
  factory ${finalClassName}.fromJson(Map<String, dynamic> _input_) {
551
- final ${discriminatorProp} = typeFromDynamic<String>(_input_["${schema.discriminator}"], "");
574
+ final ${discriminatorProp} = typeFromDynamic<String>(_input_["${tagKey}"], "");
552
575
  switch (${discriminatorProp}) {
553
576
  ${subTypeParts.map(
554
577
  (type) => ` case "${type.value}":
@@ -568,6 +591,199 @@ ${subContentParts.join("\n\n")}`;
568
591
  context.generatedTypes.push(className);
569
592
  return result;
570
593
  }
594
+ function dartWrappedUnionFromSchema(schema, context) {
595
+ const isNullable = outputIsNullable(schema, context);
596
+ const className = getDartClassName(schema, context);
597
+ const finalClassName = `${context.modelPrefix}${className}`;
598
+ const typeName = isNullable ? `${finalClassName}?` : finalClassName;
599
+ const defaultValue = isNullable ? `null` : `${finalClassName}.empty()`;
600
+ const result = {
601
+ typeName,
602
+ isNullable,
603
+ defaultValue,
604
+ fromJson(input) {
605
+ if (isNullable) {
606
+ return `${input} is Map<String, dynamic> ? ${finalClassName}.fromJson(${input}) : null`;
607
+ }
608
+ return `${input} is Map<String, dynamic> ? ${finalClassName}.fromJson(${input}) : ${finalClassName}.empty()`;
609
+ },
610
+ toJson(input) {
611
+ if (context.isOptional) {
612
+ return `${input}!.toJson()`;
613
+ }
614
+ if (schema.isNullable) {
615
+ return `${input}?.toJson()`;
616
+ }
617
+ return `${input}.toJson()`;
618
+ },
619
+ toQueryString() {
620
+ return `print(
621
+ "[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
622
+ },
623
+ content: ""
624
+ };
625
+ if (context.generatedTypes.includes(className)) {
626
+ return result;
627
+ }
628
+ const tagKey = schema.tagKey;
629
+ const tagProp = tagKey ? validDartIdentifier(tagKey) : void 0;
630
+ const valueKey = schema.valueKey ?? "value";
631
+ const valueProp = validDartIdentifier(valueKey);
632
+ const variants = [];
633
+ const variantContentParts = [];
634
+ const subContentParts = [];
635
+ for (const key of Object.keys(schema.union)) {
636
+ const subSchema = schema.union[key];
637
+ const variantClassName = `${context.modelPrefix}${validDartClassName(`${className}_${key}`, context.modelPrefix)}`;
638
+ const valueType = dartTypeFromSchema(subSchema, {
639
+ clientName: context.clientName,
640
+ modelPrefix: context.modelPrefix,
641
+ generatedTypes: context.generatedTypes,
642
+ instancePath: `/${className}/${key}/${valueKey}`,
643
+ schemaPath: `${context.schemaPath}/union/${key}`,
644
+ clientVersion: context.clientVersion
645
+ });
646
+ if (valueType.content) {
647
+ subContentParts.push(valueType.content);
648
+ }
649
+ variants.push({ key, className: variantClassName });
650
+ const jsonValueKey = tagKey ? valueKey : key;
651
+ const tagGetter = tagProp ? `
652
+ @override
653
+ String get ${tagProp} => "${key}";
654
+ ` : "";
655
+ const toJsonParts = tagProp ? ` "${tagKey}": ${tagProp},
656
+ "${jsonValueKey}": ${valueType.toJson(valueProp, "_output_", jsonValueKey)},` : ` "${jsonValueKey}": ${valueType.toJson(valueProp, "_output_", jsonValueKey)},`;
657
+ const copyWithParam = valueType.isNullable ? `${valueType.typeName} Function()? ${valueProp}` : `${valueType.typeName}${valueType.typeName !== "dynamic" ? "?" : ""} ${valueProp}`;
658
+ const copyWithReturn = valueType.isNullable ? `${valueProp}: ${valueProp} != null ? ${valueProp}() : this.${valueProp}` : `${valueProp}: ${valueProp} ?? this.${valueProp}`;
659
+ variantContentParts.push(`class ${variantClassName} implements ${finalClassName} {
660
+ final ${valueType.typeName} ${valueProp};
661
+ const ${variantClassName}({
662
+ required this.${valueProp},
663
+ });
664
+ ${tagGetter}
665
+ factory ${variantClassName}.empty() {
666
+ return ${variantClassName}(
667
+ ${valueProp}: ${valueType.defaultValue},
668
+ );
669
+ }
670
+
671
+ factory ${variantClassName}.fromJson(Map<String, dynamic> _input_) {
672
+ final ${valueProp} = ${valueType.fromJson(`_input_["${jsonValueKey}"]`, jsonValueKey)};
673
+ return ${variantClassName}(
674
+ ${valueProp}: ${valueProp},
675
+ );
676
+ }
677
+
678
+ factory ${variantClassName}.fromJsonString(String input) {
679
+ return ${variantClassName}.fromJson(json.decode(input));
680
+ }
681
+
682
+ @override
683
+ Map<String, dynamic> toJson() {
684
+ final _output_ = <String, dynamic>{
685
+ ${toJsonParts}
686
+ };
687
+ return _output_;
688
+ }
689
+
690
+ @override
691
+ String toJsonString() {
692
+ return json.encode(toJson());
693
+ }
694
+
695
+ @override
696
+ String toUrlQueryParams() {
697
+ print(
698
+ "[WARNING] unions cannot be serialized to query params. Skipping ${variantClassName}.");
699
+ return "";
700
+ }
701
+
702
+ @override
703
+ ${variantClassName} copyWith({
704
+ ${copyWithParam},
705
+ }) {
706
+ return ${variantClassName}(
707
+ ${copyWithReturn},
708
+ );
709
+ }
710
+
711
+ @override
712
+ List<Object?> get props => [
713
+ ${valueProp},
714
+ ];
715
+
716
+ @override
717
+ bool operator ==(Object other) {
718
+ return other is ${variantClassName} &&
719
+ listsAreEqual(props, other.props);
720
+ }
721
+
722
+ @override
723
+ int get hashCode => listToHashCode(props);
724
+
725
+ @override
726
+ String toString() {
727
+ return "${variantClassName} \${toJsonString()}";
728
+ }
729
+ }`);
730
+ }
731
+ const fallbackKey = codegenUtils.getUnionFallbackKey(schema.union);
732
+ const fallbackVariant = variants.find(
733
+ (variant) => variant.key === fallbackKey
734
+ );
735
+ let fromJsonBody;
736
+ if (tagKey && tagProp) {
737
+ fromJsonBody = ` final ${tagProp} = typeFromDynamic<String>(_input_["${tagKey}"], "");
738
+ switch (${tagProp}) {
739
+ ${variants.map(
740
+ (variant) => ` case "${variant.key}":
741
+ return ${variant.className}.fromJson(_input_);`
742
+ ).join("\n")}
743
+ default:
744
+ return ${finalClassName}.empty();
745
+ }`;
746
+ } else {
747
+ fromJsonBody = `${variants.map(
748
+ (variant) => ` if (_input_.containsKey("${variant.key}")) {
749
+ return ${variant.className}.fromJson(_input_);
750
+ }`
751
+ ).join("\n")}
752
+ return ${finalClassName}.empty();`;
753
+ }
754
+ result.content = `${getCodeComments(schema.metadata)}sealed class ${finalClassName} implements ArriModel {${tagProp ? `
755
+ String get ${tagProp};` : ""}
756
+ const ${finalClassName}();
757
+
758
+ factory ${finalClassName}.empty() {
759
+ return ${fallbackVariant?.className}.empty();
760
+ }
761
+
762
+ factory ${finalClassName}.fromJson(Map<String, dynamic> _input_) {
763
+ ${fromJsonBody}
764
+ }
765
+
766
+ factory ${finalClassName}.fromJsonString(String input) {
767
+ return ${finalClassName}.fromJson(json.decode(input));
768
+ }
769
+ }
770
+
771
+ ${variantContentParts.join("\n\n")}
772
+
773
+ ${subContentParts.join("\n\n")}`;
774
+ context.generatedTypes.push(className);
775
+ return result;
776
+ }
777
+
778
+ function dartSealedClassFromSchema(schema, context) {
779
+ return dartInternallyTaggedSealedClass(
780
+ schema,
781
+ schema.discriminator,
782
+ schema.mapping,
783
+ "mapping",
784
+ context
785
+ );
786
+ }
571
787
 
572
788
  function dartEnumFromSchema(schema, context) {
573
789
  const isNullable = outputIsNullable(schema, context);
@@ -604,12 +820,12 @@ function dartEnumFromSchema(schema, context) {
604
820
  },
605
821
  toQueryString(input, target, key) {
606
822
  if (context.isOptional) {
607
- return `if (${input} != null) ${target}.add("${key}=\${${input}!.serialValue}")`;
823
+ return `if (${input} != null) ${target}.add("${key}=\${Uri.encodeQueryComponent(${input}!.serialValue)}")`;
608
824
  }
609
825
  if (schema.isNullable) {
610
- return `${target}.add("${key}=\${${input}?.serialValue}")`;
826
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}?.serialValue ?? "null")}")`;
611
827
  }
612
- return `${target}.add("${key}=\${${input}.serialValue}")`;
828
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}.serialValue)}")`;
613
829
  },
614
830
  content: ""
615
831
  };
@@ -657,9 +873,12 @@ function dartStringFromSchema(schema, context) {
657
873
  },
658
874
  toQueryString(input, target, key) {
659
875
  if (context.isOptional) {
660
- return `if (${input} != null) ${target}.add("${key}=$${input}")`;
876
+ return `if (${input} != null) ${target}.add("${key}=\${Uri.encodeQueryComponent(${input}!)}")`;
661
877
  }
662
- return `${target}.add("${key}=$${input}")`;
878
+ if (isNullable) {
879
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input} ?? "null")}")`;
880
+ }
881
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input})}")`;
663
882
  },
664
883
  content: ""
665
884
  };
@@ -693,7 +912,7 @@ function dartBoolFromSchema(schema, context) {
693
912
  function dartDateTimeFromSchema(schema, context) {
694
913
  const isNullable = outputIsNullable(schema, context);
695
914
  const typeName = isNullable ? "DateTime?" : "DateTime";
696
- const defaultValue = isNullable ? "null" : "DateTime(0)";
915
+ const defaultValue = isNullable ? "null" : "DateTime.fromMillisecondsSinceEpoch(0, isUtc: true)";
697
916
  return {
698
917
  typeName,
699
918
  isNullable,
@@ -702,7 +921,7 @@ function dartDateTimeFromSchema(schema, context) {
702
921
  if (isNullable) {
703
922
  return `nullableDateTimeFromDynamic(${input})`;
704
923
  }
705
- return `dateTimeFromDynamic(${input}, DateTime(0))`;
924
+ return `dateTimeFromDynamic(${input}, ${defaultValue})`;
706
925
  },
707
926
  toJson(input, _target, _key) {
708
927
  if (context.isOptional) {
@@ -715,12 +934,12 @@ function dartDateTimeFromSchema(schema, context) {
715
934
  },
716
935
  toQueryString(input, target, key) {
717
936
  if (context.isOptional) {
718
- return `if (${input} != null) ${target}.add("${key}=\${${input}!.toUtc().toIso8601String()}")`;
937
+ return `if (${input} != null) ${target}.add("${key}=\${Uri.encodeQueryComponent(${input}!.toUtc().toIso8601String())}")`;
719
938
  }
720
939
  if (schema.isNullable) {
721
- return `${target}.add("${key}=\${${input}?.toUtc().toIso8601String()}")`;
940
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}?.toUtc().toIso8601String() ?? "null")}")`;
722
941
  }
723
- return `${target}.add("${key}=\${${input}.toUtc().toIso8601String()}")`;
942
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}.toUtc().toIso8601String())}")`;
724
943
  },
725
944
  content: ""
726
945
  };
@@ -1084,6 +1303,7 @@ function dartRefFromSchema(schema, context) {
1084
1303
  };
1085
1304
  }
1086
1305
 
1306
+ const dartFormatLanguageVersion = "3.7";
1087
1307
  const dartClientGenerator = codegenUtils.defineGeneratorPlugin(
1088
1308
  (options) => {
1089
1309
  return {
@@ -1099,7 +1319,9 @@ const dartClientGenerator = codegenUtils.defineGeneratorPlugin(
1099
1319
  const destination = path__default.resolve(options.outputFile);
1100
1320
  await fs__default.writeFile(destination, result);
1101
1321
  if (options.format !== false) {
1102
- node_child_process.execSync(`dart format ${destination}`);
1322
+ node_child_process.execSync(
1323
+ `dart format --language-version=${dartFormatLanguageVersion} ${destination}`
1324
+ );
1103
1325
  }
1104
1326
  } catch (err) {
1105
1327
  console.error(err);
@@ -1264,6 +1486,9 @@ function dartTypeFromSchema(schema, context) {
1264
1486
  if (codegenUtils.isSchemaFormDiscriminator(schema)) {
1265
1487
  return dartSealedClassFromSchema(schema, context);
1266
1488
  }
1489
+ if (codegenUtils.isSchemaFormUnion(schema)) {
1490
+ return dartUnionFromSchema(schema, context);
1491
+ }
1267
1492
  if (codegenUtils.isSchemaFormRef(schema)) {
1268
1493
  return dartRefFromSchema(schema, context);
1269
1494
  }
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { execSync } from 'node:child_process';
2
2
  import fs from 'node:fs/promises';
3
- import { camelCase, pascalCase, removeDisallowedChars, isServiceDefinition, isRpcDefinition, defineGeneratorPlugin, unflattenProcedures, isSchemaFormType, isSchemaFormEnum, isSchemaFormProperties, isSchemaFormElements, isSchemaFormValues, isSchemaFormDiscriminator, isSchemaFormRef } from '@arrirpc/codegen-utils';
3
+ import { camelCase, pascalCase, removeDisallowedChars, isSchemaFormProperties, getUnionFallbackKey, isServiceDefinition, isRpcDefinition, defineGeneratorPlugin, unflattenProcedures, isSchemaFormType, isSchemaFormEnum, isSchemaFormElements, isSchemaFormValues, isSchemaFormDiscriminator, isSchemaFormUnion, isSchemaFormRef } from '@arrirpc/codegen-utils';
4
4
  import path from 'pathe';
5
5
 
6
6
  function outputIsNullable(schema, context) {
@@ -296,7 +296,7 @@ function dartClassFromSchema(schema, context) {
296
296
  const toUrlQueryParts = [];
297
297
  if (context.discriminatorKey && context.discriminatorValue) {
298
298
  toUrlQueryParts.push(
299
- `_queryParts_.add("${context.discriminatorKey}=$${validDartIdentifier(context.discriminatorKey)}");`
299
+ `_queryParts_.add("${encodeURIComponent(context.discriminatorKey)}=${encodeURIComponent(context.discriminatorValue)}");`
300
300
  );
301
301
  }
302
302
  const copyWithParamParts = [];
@@ -329,7 +329,7 @@ function dartClassFromSchema(schema, context) {
329
329
  ` "${key}": ${typeResult.toJson(propName, "", key)},`
330
330
  );
331
331
  toUrlQueryParts.push(
332
- ` ${typeResult.toQueryString(propName, "_queryParts_", key)};`
332
+ ` ${typeResult.toQueryString(propName, "_queryParts_", encodeURIComponent(key))};`
333
333
  );
334
334
  if (typeResult.isNullable) {
335
335
  copyWithParamParts.push(
@@ -374,7 +374,7 @@ function dartClassFromSchema(schema, context) {
374
374
  ` if (${propName} != null) _output_["${key}"] = ${typeResult.toJson(propName, "_output_", key)};`
375
375
  );
376
376
  toUrlQueryParts.push(
377
- ` ${typeResult.toQueryString(propName, "_queryParts_", key)};`
377
+ ` ${typeResult.toQueryString(propName, "_queryParts_", encodeURIComponent(key))};`
378
378
  );
379
379
  copyWithParamParts.push(
380
380
  ` ${typeResult.typeName} Function()? ${propName},`
@@ -472,24 +472,43 @@ ${subContentParts.join("\n\n")}`;
472
472
  return result;
473
473
  }
474
474
 
475
- function dartSealedClassFromSchema(schema, context) {
475
+ function dartUnionFromSchema(schema, context) {
476
+ if (schema.tagKey && !schema.valueKey) {
477
+ for (const key of Object.keys(schema.union)) {
478
+ if (!isSchemaFormProperties(schema.union[key])) {
479
+ throw new Error(
480
+ `Error at ${context.schemaPath}/union/${key}: All union variants must be an object when tagKey is specified without a valueKey`
481
+ );
482
+ }
483
+ }
484
+ return dartInternallyTaggedSealedClass(
485
+ schema,
486
+ schema.tagKey,
487
+ schema.union,
488
+ "union",
489
+ context
490
+ );
491
+ }
492
+ return dartWrappedUnionFromSchema(schema, context);
493
+ }
494
+ function dartInternallyTaggedSealedClass(schema, tagKey, variants, variantsSchemaKey, context) {
476
495
  const isNullable = outputIsNullable(schema, context);
477
496
  const className = getDartClassName(schema, context);
478
497
  const finalClassName = `${context.modelPrefix}${className}`;
479
498
  const typeName = isNullable ? `${finalClassName}?` : finalClassName;
480
499
  const defaultValue = isNullable ? `null` : `${finalClassName}.empty()`;
481
- const discriminatorKey = schema.discriminator;
500
+ const discriminatorKey = tagKey;
482
501
  const subTypeParts = [];
483
502
  const subContentParts = [];
484
- for (const key of Object.keys(schema.mapping)) {
485
- const subSchema = schema.mapping[key];
503
+ for (const key of Object.keys(variants)) {
504
+ const subSchema = variants[key];
486
505
  const discriminatorValue = key;
487
506
  const subTypeResult = dartClassFromSchema(subSchema, {
488
507
  clientName: context.clientName,
489
508
  modelPrefix: context.modelPrefix,
490
509
  generatedTypes: context.generatedTypes,
491
510
  instancePath: context.instancePath,
492
- schemaPath: `${context.schemaPath}/mapping/${key}`,
511
+ schemaPath: `${context.schemaPath}/${variantsSchemaKey}/${key}`,
493
512
  discriminatorKey,
494
513
  discriminatorValue,
495
514
  discriminatorParentId: className,
@@ -524,24 +543,28 @@ function dartSealedClassFromSchema(schema, context) {
524
543
  },
525
544
  toQueryString() {
526
545
  return `print(
527
- "[WARNING] nested objects cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
546
+ "[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
528
547
  },
529
548
  content: ""
530
549
  };
531
550
  if (context.generatedTypes.includes(className)) {
532
551
  return result;
533
552
  }
534
- const discriminatorProp = validDartIdentifier(schema.discriminator);
553
+ const fallbackKey = getUnionFallbackKey(variants);
554
+ const fallbackType = subTypeParts.find(
555
+ (type) => type.value === fallbackKey
556
+ );
557
+ const discriminatorProp = validDartIdentifier(tagKey);
535
558
  result.content = `sealed class ${finalClassName} implements ArriModel {
536
559
  String get ${discriminatorProp};
537
560
  const ${finalClassName}();
538
561
 
539
562
  factory ${finalClassName}.empty() {
540
- return ${subTypeParts[0]?.name}.empty();
563
+ return ${fallbackType?.name}.empty();
541
564
  }
542
565
 
543
566
  factory ${finalClassName}.fromJson(Map<String, dynamic> _input_) {
544
- final ${discriminatorProp} = typeFromDynamic<String>(_input_["${schema.discriminator}"], "");
567
+ final ${discriminatorProp} = typeFromDynamic<String>(_input_["${tagKey}"], "");
545
568
  switch (${discriminatorProp}) {
546
569
  ${subTypeParts.map(
547
570
  (type) => ` case "${type.value}":
@@ -561,6 +584,199 @@ ${subContentParts.join("\n\n")}`;
561
584
  context.generatedTypes.push(className);
562
585
  return result;
563
586
  }
587
+ function dartWrappedUnionFromSchema(schema, context) {
588
+ const isNullable = outputIsNullable(schema, context);
589
+ const className = getDartClassName(schema, context);
590
+ const finalClassName = `${context.modelPrefix}${className}`;
591
+ const typeName = isNullable ? `${finalClassName}?` : finalClassName;
592
+ const defaultValue = isNullable ? `null` : `${finalClassName}.empty()`;
593
+ const result = {
594
+ typeName,
595
+ isNullable,
596
+ defaultValue,
597
+ fromJson(input) {
598
+ if (isNullable) {
599
+ return `${input} is Map<String, dynamic> ? ${finalClassName}.fromJson(${input}) : null`;
600
+ }
601
+ return `${input} is Map<String, dynamic> ? ${finalClassName}.fromJson(${input}) : ${finalClassName}.empty()`;
602
+ },
603
+ toJson(input) {
604
+ if (context.isOptional) {
605
+ return `${input}!.toJson()`;
606
+ }
607
+ if (schema.isNullable) {
608
+ return `${input}?.toJson()`;
609
+ }
610
+ return `${input}.toJson()`;
611
+ },
612
+ toQueryString() {
613
+ return `print(
614
+ "[WARNING] nested unions cannot be serialized to query params. Skipping field at ${context.instancePath}.")`;
615
+ },
616
+ content: ""
617
+ };
618
+ if (context.generatedTypes.includes(className)) {
619
+ return result;
620
+ }
621
+ const tagKey = schema.tagKey;
622
+ const tagProp = tagKey ? validDartIdentifier(tagKey) : void 0;
623
+ const valueKey = schema.valueKey ?? "value";
624
+ const valueProp = validDartIdentifier(valueKey);
625
+ const variants = [];
626
+ const variantContentParts = [];
627
+ const subContentParts = [];
628
+ for (const key of Object.keys(schema.union)) {
629
+ const subSchema = schema.union[key];
630
+ const variantClassName = `${context.modelPrefix}${validDartClassName(`${className}_${key}`, context.modelPrefix)}`;
631
+ const valueType = dartTypeFromSchema(subSchema, {
632
+ clientName: context.clientName,
633
+ modelPrefix: context.modelPrefix,
634
+ generatedTypes: context.generatedTypes,
635
+ instancePath: `/${className}/${key}/${valueKey}`,
636
+ schemaPath: `${context.schemaPath}/union/${key}`,
637
+ clientVersion: context.clientVersion
638
+ });
639
+ if (valueType.content) {
640
+ subContentParts.push(valueType.content);
641
+ }
642
+ variants.push({ key, className: variantClassName });
643
+ const jsonValueKey = tagKey ? valueKey : key;
644
+ const tagGetter = tagProp ? `
645
+ @override
646
+ String get ${tagProp} => "${key}";
647
+ ` : "";
648
+ const toJsonParts = tagProp ? ` "${tagKey}": ${tagProp},
649
+ "${jsonValueKey}": ${valueType.toJson(valueProp, "_output_", jsonValueKey)},` : ` "${jsonValueKey}": ${valueType.toJson(valueProp, "_output_", jsonValueKey)},`;
650
+ const copyWithParam = valueType.isNullable ? `${valueType.typeName} Function()? ${valueProp}` : `${valueType.typeName}${valueType.typeName !== "dynamic" ? "?" : ""} ${valueProp}`;
651
+ const copyWithReturn = valueType.isNullable ? `${valueProp}: ${valueProp} != null ? ${valueProp}() : this.${valueProp}` : `${valueProp}: ${valueProp} ?? this.${valueProp}`;
652
+ variantContentParts.push(`class ${variantClassName} implements ${finalClassName} {
653
+ final ${valueType.typeName} ${valueProp};
654
+ const ${variantClassName}({
655
+ required this.${valueProp},
656
+ });
657
+ ${tagGetter}
658
+ factory ${variantClassName}.empty() {
659
+ return ${variantClassName}(
660
+ ${valueProp}: ${valueType.defaultValue},
661
+ );
662
+ }
663
+
664
+ factory ${variantClassName}.fromJson(Map<String, dynamic> _input_) {
665
+ final ${valueProp} = ${valueType.fromJson(`_input_["${jsonValueKey}"]`, jsonValueKey)};
666
+ return ${variantClassName}(
667
+ ${valueProp}: ${valueProp},
668
+ );
669
+ }
670
+
671
+ factory ${variantClassName}.fromJsonString(String input) {
672
+ return ${variantClassName}.fromJson(json.decode(input));
673
+ }
674
+
675
+ @override
676
+ Map<String, dynamic> toJson() {
677
+ final _output_ = <String, dynamic>{
678
+ ${toJsonParts}
679
+ };
680
+ return _output_;
681
+ }
682
+
683
+ @override
684
+ String toJsonString() {
685
+ return json.encode(toJson());
686
+ }
687
+
688
+ @override
689
+ String toUrlQueryParams() {
690
+ print(
691
+ "[WARNING] unions cannot be serialized to query params. Skipping ${variantClassName}.");
692
+ return "";
693
+ }
694
+
695
+ @override
696
+ ${variantClassName} copyWith({
697
+ ${copyWithParam},
698
+ }) {
699
+ return ${variantClassName}(
700
+ ${copyWithReturn},
701
+ );
702
+ }
703
+
704
+ @override
705
+ List<Object?> get props => [
706
+ ${valueProp},
707
+ ];
708
+
709
+ @override
710
+ bool operator ==(Object other) {
711
+ return other is ${variantClassName} &&
712
+ listsAreEqual(props, other.props);
713
+ }
714
+
715
+ @override
716
+ int get hashCode => listToHashCode(props);
717
+
718
+ @override
719
+ String toString() {
720
+ return "${variantClassName} \${toJsonString()}";
721
+ }
722
+ }`);
723
+ }
724
+ const fallbackKey = getUnionFallbackKey(schema.union);
725
+ const fallbackVariant = variants.find(
726
+ (variant) => variant.key === fallbackKey
727
+ );
728
+ let fromJsonBody;
729
+ if (tagKey && tagProp) {
730
+ fromJsonBody = ` final ${tagProp} = typeFromDynamic<String>(_input_["${tagKey}"], "");
731
+ switch (${tagProp}) {
732
+ ${variants.map(
733
+ (variant) => ` case "${variant.key}":
734
+ return ${variant.className}.fromJson(_input_);`
735
+ ).join("\n")}
736
+ default:
737
+ return ${finalClassName}.empty();
738
+ }`;
739
+ } else {
740
+ fromJsonBody = `${variants.map(
741
+ (variant) => ` if (_input_.containsKey("${variant.key}")) {
742
+ return ${variant.className}.fromJson(_input_);
743
+ }`
744
+ ).join("\n")}
745
+ return ${finalClassName}.empty();`;
746
+ }
747
+ result.content = `${getCodeComments(schema.metadata)}sealed class ${finalClassName} implements ArriModel {${tagProp ? `
748
+ String get ${tagProp};` : ""}
749
+ const ${finalClassName}();
750
+
751
+ factory ${finalClassName}.empty() {
752
+ return ${fallbackVariant?.className}.empty();
753
+ }
754
+
755
+ factory ${finalClassName}.fromJson(Map<String, dynamic> _input_) {
756
+ ${fromJsonBody}
757
+ }
758
+
759
+ factory ${finalClassName}.fromJsonString(String input) {
760
+ return ${finalClassName}.fromJson(json.decode(input));
761
+ }
762
+ }
763
+
764
+ ${variantContentParts.join("\n\n")}
765
+
766
+ ${subContentParts.join("\n\n")}`;
767
+ context.generatedTypes.push(className);
768
+ return result;
769
+ }
770
+
771
+ function dartSealedClassFromSchema(schema, context) {
772
+ return dartInternallyTaggedSealedClass(
773
+ schema,
774
+ schema.discriminator,
775
+ schema.mapping,
776
+ "mapping",
777
+ context
778
+ );
779
+ }
564
780
 
565
781
  function dartEnumFromSchema(schema, context) {
566
782
  const isNullable = outputIsNullable(schema, context);
@@ -597,12 +813,12 @@ function dartEnumFromSchema(schema, context) {
597
813
  },
598
814
  toQueryString(input, target, key) {
599
815
  if (context.isOptional) {
600
- return `if (${input} != null) ${target}.add("${key}=\${${input}!.serialValue}")`;
816
+ return `if (${input} != null) ${target}.add("${key}=\${Uri.encodeQueryComponent(${input}!.serialValue)}")`;
601
817
  }
602
818
  if (schema.isNullable) {
603
- return `${target}.add("${key}=\${${input}?.serialValue}")`;
819
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}?.serialValue ?? "null")}")`;
604
820
  }
605
- return `${target}.add("${key}=\${${input}.serialValue}")`;
821
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}.serialValue)}")`;
606
822
  },
607
823
  content: ""
608
824
  };
@@ -650,9 +866,12 @@ function dartStringFromSchema(schema, context) {
650
866
  },
651
867
  toQueryString(input, target, key) {
652
868
  if (context.isOptional) {
653
- return `if (${input} != null) ${target}.add("${key}=$${input}")`;
869
+ return `if (${input} != null) ${target}.add("${key}=\${Uri.encodeQueryComponent(${input}!)}")`;
654
870
  }
655
- return `${target}.add("${key}=$${input}")`;
871
+ if (isNullable) {
872
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input} ?? "null")}")`;
873
+ }
874
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input})}")`;
656
875
  },
657
876
  content: ""
658
877
  };
@@ -686,7 +905,7 @@ function dartBoolFromSchema(schema, context) {
686
905
  function dartDateTimeFromSchema(schema, context) {
687
906
  const isNullable = outputIsNullable(schema, context);
688
907
  const typeName = isNullable ? "DateTime?" : "DateTime";
689
- const defaultValue = isNullable ? "null" : "DateTime(0)";
908
+ const defaultValue = isNullable ? "null" : "DateTime.fromMillisecondsSinceEpoch(0, isUtc: true)";
690
909
  return {
691
910
  typeName,
692
911
  isNullable,
@@ -695,7 +914,7 @@ function dartDateTimeFromSchema(schema, context) {
695
914
  if (isNullable) {
696
915
  return `nullableDateTimeFromDynamic(${input})`;
697
916
  }
698
- return `dateTimeFromDynamic(${input}, DateTime(0))`;
917
+ return `dateTimeFromDynamic(${input}, ${defaultValue})`;
699
918
  },
700
919
  toJson(input, _target, _key) {
701
920
  if (context.isOptional) {
@@ -708,12 +927,12 @@ function dartDateTimeFromSchema(schema, context) {
708
927
  },
709
928
  toQueryString(input, target, key) {
710
929
  if (context.isOptional) {
711
- return `if (${input} != null) ${target}.add("${key}=\${${input}!.toUtc().toIso8601String()}")`;
930
+ return `if (${input} != null) ${target}.add("${key}=\${Uri.encodeQueryComponent(${input}!.toUtc().toIso8601String())}")`;
712
931
  }
713
932
  if (schema.isNullable) {
714
- return `${target}.add("${key}=\${${input}?.toUtc().toIso8601String()}")`;
933
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}?.toUtc().toIso8601String() ?? "null")}")`;
715
934
  }
716
- return `${target}.add("${key}=\${${input}.toUtc().toIso8601String()}")`;
935
+ return `${target}.add("${key}=\${Uri.encodeQueryComponent(${input}.toUtc().toIso8601String())}")`;
717
936
  },
718
937
  content: ""
719
938
  };
@@ -1077,6 +1296,7 @@ function dartRefFromSchema(schema, context) {
1077
1296
  };
1078
1297
  }
1079
1298
 
1299
+ const dartFormatLanguageVersion = "3.7";
1080
1300
  const dartClientGenerator = defineGeneratorPlugin(
1081
1301
  (options) => {
1082
1302
  return {
@@ -1092,7 +1312,9 @@ const dartClientGenerator = defineGeneratorPlugin(
1092
1312
  const destination = path.resolve(options.outputFile);
1093
1313
  await fs.writeFile(destination, result);
1094
1314
  if (options.format !== false) {
1095
- execSync(`dart format ${destination}`);
1315
+ execSync(
1316
+ `dart format --language-version=${dartFormatLanguageVersion} ${destination}`
1317
+ );
1096
1318
  }
1097
1319
  } catch (err) {
1098
1320
  console.error(err);
@@ -1257,6 +1479,9 @@ function dartTypeFromSchema(schema, context) {
1257
1479
  if (isSchemaFormDiscriminator(schema)) {
1258
1480
  return dartSealedClassFromSchema(schema, context);
1259
1481
  }
1482
+ if (isSchemaFormUnion(schema)) {
1483
+ return dartUnionFromSchema(schema, context);
1484
+ }
1260
1485
  if (isSchemaFormRef(schema)) {
1261
1486
  return dartRefFromSchema(schema, context);
1262
1487
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arrirpc/codegen-dart",
3
- "version": "0.84.1",
3
+ "version": "0.86.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -23,6 +23,6 @@
23
23
  ],
24
24
  "dependencies": {
25
25
  "pathe": "^2.0.3",
26
- "@arrirpc/codegen-utils": "0.84.1"
26
+ "@arrirpc/codegen-utils": "0.86.0"
27
27
  }
28
28
  }