// SPDX-License-Identifier: AGPL-3.0-or-later // Generates Dart models from the schemas in api/openapi.yaml. // // dart run tool/generate_api.dart (from Phone-App/) // // Handles what the contract uses: objects, string enums, $ref, arrays, maps // (additionalProperties), "object or null" and allOf of objects (merged into // one class). Inline objects and enums become // classes named after their parent and property (WorkspaceMember.user -> // WorkspaceMemberUser). import 'dart:io'; import 'package:yaml/yaml.dart'; const _specPath = '../api/openapi.yaml'; const _outPath = 'lib/api/generated/models.dart'; void main() { final spec = loadYaml(File(_specPath).readAsStringSync()) as YamlMap; final schemas = (spec['components'] as YamlMap)['schemas'] as YamlMap; final gen = _Generator(schemas, { for (final e in schemas.entries) if ((e.value as YamlMap)['enum'] != null) e.key as String, }); for (final entry in schemas.entries) { gen.schema(_className(entry.key as String), entry.value as YamlMap); } File(_outPath) ..createSync(recursive: true) ..writeAsStringSync(gen.render()); final fmt = Process.runSync('dart', ['format', _outPath], runInShell: true); if (fmt.exitCode != 0) { stderr.write(fmt.stderr); exit(fmt.exitCode); } stdout.writeln('wrote $_outPath (${schemas.length} schemas)'); } /// Schema names that would hide a dart:core type get an Api prefix (Error -> ApiError). const _coreNames = { 'Error', 'Exception', 'Object', 'Type', 'List', 'Map', 'Set', 'Duration', 'Uri', }; String _className(String schema) => _coreNames.contains(schema) ? 'Api$schema' : schema; class _Field { _Field(this.name, this.type, this.required, this.description); final String name; final _Type type; final bool required; final String? description; } /// A Dart type plus how to convert it from and to JSON. class _Type { _Type(this.dart, this.fromJson, this.toJson, {this.nullable = false}); final String dart; final String Function(String v) fromJson; final String Function(String v) toJson; final bool nullable; } class _Generator { _Generator(this.schemas, this.enumSchemas); final YamlMap schemas; final Set enumSchemas; final _out = []; // Classes and enums written so far; an allOf reuses its parts' inline types. final _done = {}; String render() => [ '// SPDX-License-Identifier: AGPL-3.0-or-later', '', '// Code generated by tool/generate_api.dart from api/openapi.yaml. DO NOT EDIT.', '', '// ignore_for_file: constant_identifier_names', '', ..._out, ].join('\n'); void schema(String name, YamlMap s) { if (s['enum'] != null) { _enum(name, s); } else if (s['allOf'] != null) { _class(name, _merge(name, s)); } else if (s['type'] == 'object') { _class(name, s); } else { throw UnsupportedError('schema $name: type ${s['type']}'); } } void _enum(String name, YamlMap s) { if (!_done.add(name)) return; final values = (s['enum'] as YamlList).cast(); final b = StringBuffer(); _doc(b, s['description'] as String?, ''); b.writeln('enum $name {'); for (final v in values) { // An empty value means "none" (e.g. SpaceCallerRole), "*" means all // (WebhookEvent). final id = v.isEmpty ? 'none' : (v == '*' ? 'all' : _ident(v)); b.writeln(" $id('$v'),"); } b.writeln(' ;'); b.writeln(); b.writeln(' const $name(this.value);'); b.writeln(' final String value;'); b.writeln(); b.writeln(' static $name fromJson(String value) =>'); b.writeln(' values.firstWhere((e) => e.value == value,'); b.writeln( " orElse: () => throw FormatException('unknown $name', value));", ); b.writeln(); b.writeln(' String toJson() => value;'); b.writeln('}'); _out.add(b.toString()); } /// Merges the object schemas of an allOf ($refs included) into one. Inline /// types keep the name of the schema they come from (ApiToken.scope stays /// ApiTokenScope in NewApiToken). Map _merge(String name, YamlMap s) { final props = {}; final owners = {}; final required = []; for (final part in (s['allOf'] as YamlList).cast()) { final ref = part[r'$ref'] as String?; final o = ref == null ? part : schemas[ref.split('/').last] as YamlMap; if (o['type'] != 'object') { throw UnsupportedError('schema $name: allOf of non-objects'); } final p = (o['properties'] as Map?) ?? const {}; props.addAll(p); for (final k in p.keys) { owners[k as String] = ref == null ? name : _className(ref.split('/').last); } required.addAll(((o['required'] as List?) ?? const []).cast()); } return { 'type': 'object', 'description': s['description'], 'required': required, 'properties': props, 'owners': owners, }; } void _class(String name, Map s) { if (!_done.add(name)) return; final owners = (s['owners'] as Map?) ?? const {}; final required = ((s['required'] as List?) ?? const []).cast(); final props = (s['properties'] as Map?) ?? const {}; final fields = <_Field>[]; for (final e in props.entries) { final prop = e.key as String; final ps = e.value as YamlMap; fields.add( _Field( prop, _type((owners[prop] ?? name) + _pascal(prop), ps), required.contains(prop), ps['description'] as String?, ), ); } final b = StringBuffer(); _doc(b, s['description'] as String?, ''); b.writeln('class $name {'); if (fields.isEmpty) { b.writeln(' const $name();'); } else { b.writeln(' const $name({'); for (final f in fields) { b.writeln( ' ${f.required ? 'required ' : ''}this.${_ident(f.name)},', ); } b.writeln(' });'); } b.writeln(); b.writeln(' factory $name.fromJson(Map json) => $name('); for (final f in fields) { final v = "json['${f.name}']"; final conv = f.required && !f.type.nullable ? f.type.fromJson(v) : '$v == null ? null : ${f.type.fromJson(v)}'; b.writeln(' ${_ident(f.name)}: $conv,'); } b.writeln(' );'); for (final f in fields) { b.writeln(); _doc(b, f.description, ' '); final opt = !f.required || f.type.nullable; b.writeln(' final ${f.type.dart}${opt ? '?' : ''} ${_ident(f.name)};'); } b.writeln(); b.writeln(' Map toJson() => {'); for (final f in fields) { final id = _ident(f.name); // `id?` short-circuits the conversion chain when the value is null. final plain = f.type.toJson('x') == 'x'; final maybe = plain ? id : f.type.toJson('$id?'); if (f.required) { b.writeln( " '${f.name}': ${f.type.nullable ? maybe : f.type.toJson(id)},", ); } else { b.writeln(" '${f.name}': ?$maybe,"); } } b.writeln(' };'); b.writeln('}'); _out.add(b.toString()); } _Type _type(String inlineName, YamlMap s) { final ref = s[r'$ref'] as String?; if (ref != null) { final target = _className(ref.split('/').last); return _Type( target, (v) => '$target.fromJson($v as ${_isEnumRef(s) ? 'String' : 'Map'})', (v) => '$v.toJson()', ); } final oneOf = s['oneOf'] as YamlList?; if (oneOf != null) { final nonNull = oneOf .cast() .where((o) => o['type'] != 'null') .toList(); if (nonNull.length != 1 || nonNull.length == oneOf.length) { throw UnsupportedError( '$inlineName: only "T or null" oneOf is supported', ); } final t = _type(inlineName, nonNull.single); return _Type(t.dart, t.fromJson, t.toJson, nullable: true); } if (s['enum'] != null) { _enum(inlineName, s); return _Type( inlineName, (v) => '$inlineName.fromJson($v as String)', (v) => '$v.toJson()', ); } switch (s['type']) { // No type at all: any JSON value (DocRule.value). case null: return _Type('Object', (v) => '$v as Object', (v) => v); case 'string': return _Type('String', (v) => '$v as String', (v) => v); case 'integer': return _Type('int', (v) => '($v as num).toInt()', (v) => v); case 'number': return _Type('double', (v) => '($v as num).toDouble()', (v) => v); case 'boolean': return _Type('bool', (v) => '$v as bool', (v) => v); case 'array': final item = _type(inlineName, s['items'] as YamlMap); return _Type( 'List<${item.dart}>', (v) => '($v as List).map((e) => ${item.fromJson('e')}).toList()', (v) => '$v.map((e) => ${item.toJson('e')}).toList()', ); case 'object': final extra = s['additionalProperties']; if (s['properties'] != null) { _class(inlineName, s); return _Type( inlineName, (v) => '$inlineName.fromJson($v as Map)', (v) => '$v.toJson()', ); } if (extra is YamlMap) { final val = _type(inlineName, extra); final plain = val.toJson('e') == 'e'; return _Type( 'Map', (v) => '($v as Map).map((k, e) => MapEntry(k, ${val.fromJson('e')}))', (v) => plain ? v : '$v.map((k, e) => MapEntry(k, ${val.toJson('e')}))', ); } return _Type( 'Map', (v) => '$v as Map', (v) => v, ); } throw UnsupportedError('$inlineName: type ${s['type']}'); } // Enum schemas are referenced by name; the spec's enums are all strings. bool _isEnumRef(YamlMap s) => enumSchemas.contains((s[r'$ref'] as String).split('/').last); static void _doc(StringBuffer b, String? text, String indent) { if (text == null) return; for (final line in text.trim().split('\n')) { // Angle brackets would read as HTML in dartdoc, so code-span them. final doc = line.trim().replaceAllMapped( RegExp(r'<[^<>\s]+>'), (m) => '`${m[0]}`', ); b.writeln('$indent/// $doc'); } } static String _pascal(String s) => s[0].toUpperCase() + s.substring(1); static const _reserved = { 'default', 'enum', 'class', 'new', 'switch', 'in', 'is', 'continue', 'break', 'return', 'case', }; static String _ident(String s) { final id = s.replaceAllMapped( RegExp(r'[-_. ](\w)'), (m) => m[1]!.toUpperCase(), ); return _reserved.contains(id) ? '${id}_' : id; } }