Files
Docwell/Phone-App/tool/generate_api.dart
T
tajniak81andClaude Opus 5.5 ec11abd8b8 Add page properties, tags, All docs, collections and journals
Phase B (items 1-6) of docs/AFFINE.md.

Properties: workspaces define custom page properties (text, number,
checkbox, date, select, multi-select, person, link) in the new
workspace_properties collection; pages keep their values in
pages.properties, checked against each property's type. The Info panel
under the title shows tags, custom and built-in properties, following
each property's visibility; the Info side panel shows them all, with the
page's collections and the journal. Settings gains Page properties and
Tags sections.

Tags: coloured, per workspace (tags collection, pages.tags); create from
the picker, rename, recolour, merge and delete. Search filters by tag.

All docs: GET /workspaces/{id}/docs lists the pages the caller can open
with their properties, narrowed by space, tag, collection or filter
rules evaluated on the server. The view shows a list, grid or cards,
groups and orders by any property, picks the properties shown, and acts
on several pages at once (tag, move, trash, collect).

Collections (page_collections): saved rules plus pages added or taken
out by hand, private to their creator until shared with the workspace,
listed in the sidebar.

Journals: one page per person and day in a private journal space
(spaces.journal_owner) that workspace admins do not see into, made on
first use. A week strip marks days with pages, new days can start from
a template, and dates in read mode open that day's journal.

The migration and schema snapshot, OpenAPI spec and generated Go, TS and
Dart types are updated (the Dart generator learns untyped values), the
mobile editor bundle is rebuilt, the new strings are translated into all
five languages, and the user guide covers the new features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:35:42 +01:00

350 lines
11 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), "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<String> enumSchemas;
final _out = <String>[];
// Classes and enums written so far; an allOf reuses its parts' inline types.
final _done = <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['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<String>();
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<String, Object?> _merge(String name, YamlMap s) {
final props = <Object?, Object?>{};
final owners = <String, String>{};
final required = <String>[];
for (final part in (s['allOf'] as YamlList).cast<YamlMap>()) {
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<String>());
}
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<String, String>?) ?? const {};
final required = ((s['required'] as List?) ?? const []).cast<String>();
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<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']) {
// 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<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')) {
// 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',
};
static String _ident(String s) {
final id = s.replaceAllMapped(
RegExp(r'[-_. ](\w)'),
(m) => m[1]!.toUpperCase(),
);
return _reserved.contains(id) ? '${id}_' : id;
}
}