Files
Docwell/Phone-App/tool/generate_api.dart
T
tajniak81andClaude Opus 5.5 ba394b8fac Finish Phase 0: lint, codegen, contributor docs and the two remaining spikes
Repository basics:
- CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1)
- SPDX AGPL-3.0-or-later headers on all hand-written sources, checked in CI
- golangci-lint (shared .golangci.yml), ESLint and Prettier, all run in CI

API codegen from api/openapi.yaml (npm run generate, drift fails CI):
- Go types via oapi-codegen in Server/internal/api
- a contract test that the router and the spec list the same routes
- Dart models via Phone-App/tool/generate_api.dart; the app uses them

Spike: shared Tiptap editor in a Flutter WebView (ADR-4)
- @docwell/editor-bridge builds the editor into one HTML page with a
  versioned JSON protocol; Phone-App hosts it with webview_flutter and a
  native toolbar. Integration test passes on an Android API 35 emulator.
- flutter_inappwebview dropped: its Android plugin fails on AGP 9.

Spike: Wails v3 desktop (ADR-11)
- system tray, docwell:// deep links (page and space only) with
  single-instance hand-off, and the built-in updater with a required
  ed25519 signing key. Verified on Windows.
- regenerated build assets register the scheme and drop template
  placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:11:07 +01:00

300 lines
8.8 KiB
Dart

// 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) and "object or null". 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({
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.enumSchemas);
final Set<String> enumSchemas;
final _out = <String>[];
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['type'] == 'object') {
_class(name, s);
} else {
throw UnsupportedError('schema $name: type ${s['type']}');
}
}
void _enum(String name, YamlMap s) {
final values = (s['enum'] as YamlList).cast<String>();
final b = StringBuffer();
_doc(b, s['description'] as String?, '');
b.writeln('enum $name {');
for (final v in values) {
b.writeln(" ${_ident(v)}('$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());
}
void _class(String name, YamlMap s) {
final required = ((s['required'] as YamlList?) ?? YamlList())
.cast<String>();
final props = (s['properties'] as YamlMap?) ?? YamlMap();
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(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<String, dynamic> 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<String, dynamic> 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<String, dynamic>'})',
(v) => '$v.toJson()',
);
}
final oneOf = s['oneOf'] as YamlList?;
if (oneOf != null) {
final nonNull = oneOf
.cast<YamlMap>()
.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']) {
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<String, dynamic>)',
(v) => '$v.toJson()',
);
}
if (extra is YamlMap) {
final val = _type(inlineName, extra);
final plain = val.toJson('e') == 'e';
return _Type(
'Map<String, ${val.dart}>',
(v) =>
'($v as Map<String, dynamic>).map((k, e) => MapEntry(k, ${val.fromJson('e')}))',
(v) =>
plain ? v : '$v.map((k, e) => MapEntry(k, ${val.toJson('e')}))',
);
}
return _Type(
'Map<String, dynamic>',
(v) => '$v as Map<String, dynamic>',
(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')) {
b.writeln('$indent/// ${line.trim()}');
}
}
static String _pascal(String s) => s[0].toUpperCase() + s.substring(1);
static const _reserved = {
'default',
'enum',
'class',
'new',
'switch',
'in',
'is',
};
static String _ident(String s) {
final id = s.replaceAllMapped(
RegExp(r'[-_ ](\w)'),
(m) => m[1]!.toUpperCase(),
);
return _reserved.contains(id) ? '${id}_' : id;
}
}