// Drop-in Dart client library for the Sourdough Tracker HTTP API. // // Save this file under your project as `lib/sourdough_client.dart` and // import it directly: // // import 'package:my_project/sourdough_client.dart'; // // final c = SourdoughClient('pat_...'); // final rows = await c.accountList(opts: ListOpts(limit: 20, sort: '-created_at')); // final fresh = await c.accountCreate({{'name': 'Example GmbH'}}); // // Every endpoint exposed by the HTTP API is wrapped as a typed // `` method on SourdoughClient. List endpoints take an optional // ListOpts; get/update/delete endpoints take the row id as the first // argument. // // Provided as-is, with no warranty. Vendor freely; modify as needed. // Targets Dart 3.0+; uses only the platform stdlib (`dart:io`, // `dart:convert`, `dart:async`). // // DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. // Local edits will be overwritten by the once-per-day version check. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; // ── Identity (substituted at generation time) ──────────────────────── const String appSlug = 'sourdough'; const String appName = 'Sourdough Tracker'; const String moduleName = 'sourdough_client'; const String clientVersion = '0.3.13'; const String language = 'dart'; const String _defaultBase = 'https://sourdoughtracker.com'; /// Per-type metadata baked at generation time. Decoded once on first /// access; useful at runtime when calling code needs to know the legal /// filters / sort columns / max_limit for a model without a second /// round-trip. final Map types = json.decode(r'''{"log_entry":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","kind","title","body","occurred_at","rise_pct","aroma_score","bubble_activity","hydration_pct","flour_used","water_temp_c","ambient_temp_c","feeding_ratio","bake_recipe","bake_outcome","loaf_count","tags"],"update_fields":["kind","title","body","occurred_at","rise_pct","aroma_score","bubble_activity","hydration_pct","flour_used","water_temp_c","ambient_temp_c","feeding_ratio","bake_recipe","bake_outcome","loaf_count","tags"],"allowed_filters":["data__parent_id","data__kind","data__bake_outcome","status","is_archived","owned_by"],"allowed_sorts":["data__occurred_at","created_at","updated_at"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"body","type":"string","max_len":8000},{"name":"kind","type":"enum","values":["feed","bake","observation","milestone","photo"]},{"name":"tags","type":"tags"},{"name":"title","type":"string","max_len":200},{"name":"rise_pct","type":"number"},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"sourdough","owned":true,"optional":false}},{"name":"flour_used","type":"string","max_len":200},{"name":"loaf_count","type":"number"},{"name":"aroma_score","type":"number"},{"name":"bake_recipe","type":"string","max_len":4000},{"name":"occurred_at","type":"string","max_len":32},{"name":"bake_outcome","type":"enum","values":["amazing","great","ok","dense","flat","undercooked","overcooked"]},{"name":"water_temp_c","type":"number"},{"name":"feeding_ratio","type":"string","max_len":32},{"name":"hydration_pct","type":"number"},{"name":"ambient_temp_c","type":"number"},{"name":"bubble_activity","type":"number"}]},"sourdough":{"ops":["list","read","create","update","delete"],"create_fields":["name","slug","source","started_at","flour_type","hydration_pct","feeding_ratio","feeding_freq_hours","ambient_temp_c","last_fed_at","retired","favorite","tags","color","notes"],"update_fields":["name","slug","source","started_at","flour_type","hydration_pct","feeding_ratio","feeding_freq_hours","ambient_temp_c","last_fed_at","retired","favorite","tags","color","notes"],"allowed_filters":["data__name","data__slug","data__flour_type","data__retired","data__favorite","data__tags","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__name","data__started_at","data__last_fed_at"],"default_sort":"data__name","max_limit":200,"fields":[{"name":"mode","type":"enum","values":["establishing","maintenance","activating","baking"]},{"name":"name","type":"string","max_len":120},{"name":"slug","type":"string","max_len":120},{"name":"tags","type":"tags"},{"name":"color","type":"string","max_len":24},{"name":"notes","type":"string","max_len":8000},{"name":"source","type":"string","max_len":200},{"name":"retired","type":"bool"},{"name":"favorite","type":"bool"},{"name":"flour_type","type":"enum","values":["white","whole_wheat","rye","spelt","einkorn","khorasan","mixed","other"]},{"name":"started_at","type":"string","max_len":32},{"name":"last_fed_at","type":"string","max_len":32},{"name":"establish_day","type":"number"},{"name":"feeding_ratio","type":"string","max_len":32},{"name":"hydration_pct","type":"number"},{"name":"ambient_temp_c","type":"number"},{"name":"computed_state","type":"string","max_len":64},{"name":"bake_target_date","type":"string","max_len":32},{"name":"feeding_freq_hours","type":"number"},{"name":"establish_started_at","type":"string","max_len":32},{"name":"establish_step_done_at","type":"string","max_len":64},{"name":"establish_next_remind_at","type":"string","max_len":64}]}}''') as Map; class ApiError implements Exception { final int status; final String message; final dynamic bodyRaw; ApiError(this.status, this.message, [this.bodyRaw]); @override String toString() => 'HTTP $status: $message'; } class ListOpts { final int? limit; final int? offset; final String? sort; final String? q; final Map? filters; ListOpts({this.limit, this.offset, this.sort, this.q, this.filters}); } class SourdoughClient { String _baseUrl; String _token; late final String _deviceId; late final String _sessionId; bool _autoupdateAttempted = false; bool _metaSentOnce = false; final HttpClient _http = HttpClient(); static const Set _retryableStatuses = {408, 425, 429, 500, 502, 503, 504}; static const int _maxRetries = 3; static const Duration _defaultTimeout = Duration(seconds: 30); SourdoughClient([String token = '']) : _baseUrl = _resolveBaseUrl(), _token = token.isNotEmpty ? token : (Platform.environment['XCLIENT_TOKEN'] ?? '') { _deviceId = _loadOrMintDeviceId(); _sessionId = _mintUuid(); _http.connectionTimeout = const Duration(seconds: 15); } void setToken(String token) { _token = token; } void setBaseUrl(String url) { _baseUrl = _trimRightSlash(url); } static String _trimRightSlash(String s) { var out = s; while (out.endsWith('/')) { out = out.substring(0, out.length - 1); } return out; } static String _resolveBaseUrl() { final env = Platform.environment['XCLIENT_BASE_URL']; return _trimRightSlash((env != null && env.isNotEmpty) ? env : _defaultBase); } // ── Identifier persistence ───────────────────────────────────────── static String? _stateDir() { final home = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; if (home == null || home.isEmpty) return null; final d = '$home/.${moduleName}'; try { Directory(d).createSync(recursive: true); return d; } catch (_) { return null; } } static String _mintUuid() { final rng = Random.secure(); final bytes = List.generate(16, (_) => rng.nextInt(256)); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; String hx(int i) => bytes[i].toRadixString(16).padLeft(2, '0'); return '${hx(0)}${hx(1)}${hx(2)}${hx(3)}-${hx(4)}${hx(5)}-${hx(6)}${hx(7)}-${hx(8)}${hx(9)}-${hx(10)}${hx(11)}${hx(12)}${hx(13)}${hx(14)}${hx(15)}'; } static String _loadOrMintDeviceId() { final d = _stateDir(); if (d == null) return _mintUuid(); final f = File('$d/device.json'); if (f.existsSync()) { try { final blob = json.decode(f.readAsStringSync()) as Map; final did = blob['device_id']; if (did is String && did.length >= 32) return did; } catch (_) {} } final fresh = _mintUuid(); try { f.writeAsStringSync(json.encode({'device_id': fresh})); } catch (_) {} return fresh; } static bool _autoupdateEnabled() { final v = (Platform.environment['XCLIENT_NO_AUTOUPDATE'] ?? '').toLowerCase(); return v != '1' && v != 'true' && v != 'yes'; } static Map _fingerprint() { final env = Platform.environment; final tp = (env['TERM_PROGRAM'] ?? '').toLowerCase(); return { 'dart_version': Platform.version, 'os': Platform.operatingSystem, 'os_version': Platform.operatingSystemVersion, 'term_program': env['TERM_PROGRAM'], 'editor_env': env['EDITOR'], 'ci': env.containsKey('CI') || env.containsKey('GITHUB_ACTIONS'), 'claude_code': env.containsKey('CLAUDECODE') || env.containsKey('CLAUDE_CODE_ENTRYPOINT'), 'codex': env.containsKey('CODEX_HOME'), 'vscode': tp == 'vscode' && !env.containsKey('CURSOR_TRACE_ID'), 'cursor': env.containsKey('CURSOR_TRACE_ID'), 'antigravity': env.containsKey('ANTIGRAVITY_TRACE_ID'), 'jetbrains': tp.contains('jetbrains'), }; } String _userAgent() => '$moduleName/$clientVersion (lib/$language; dart/${Platform.version.split(' ').first}; ${Platform.operatingSystem})'; static double _backoffSeconds(int attempt, double? retryAfter) { if (retryAfter != null && retryAfter >= 0) return min(retryAfter, 60.0); return min(pow(2, attempt).toDouble(), 60.0); } // ── HTTP transport ───────────────────────────────────────────────── /// Generic request helper. JSON in / JSON out. Future?> requestJson( String method, String path, dynamic body) async { _maybeAutoupdate(); Object? lastErr; for (var attempt = 0; attempt < _maxRetries; attempt++) { try { final result = await _sendFollowingRedirects( method.toUpperCase(), '$_baseUrl$path', body); final status = result.status; final headers = result.headers; final raw = result.body; final fresh = headers['x-auth-refresh-token']; if (fresh != null && fresh.isNotEmpty) _token = fresh; if (_retryableStatuses.contains(status) && attempt + 1 < _maxRetries) { double? ra; final raStr = headers['retry-after']; if (raStr != null) ra = double.tryParse(raStr); await Future.delayed( Duration(milliseconds: (_backoffSeconds(attempt, ra) * 1000).round())); continue; } dynamic parsed; if (raw.isNotEmpty) { try { parsed = json.decode(raw); } catch (_) { parsed = null; } } if (status >= 400) { var msg = 'request failed'; if (parsed is Map) { final d = parsed['detail']; final m = parsed['message']; if (d is String) msg = d; else if (m is String) msg = m; } _emitCallEvent(method, path, status, false); throw ApiError(status, msg, parsed); } _emitCallEvent(method, path, status, true); if (parsed is Map) return parsed; return null; } on ApiError { rethrow; } catch (e) { lastErr = e; if (attempt + 1 < _maxRetries) { await Future.delayed( Duration(milliseconds: (_backoffSeconds(attempt, null) * 1000).round())); continue; } _emitCallEvent(method, path, 0, false); throw ApiError(0, e.toString()); } } _emitCallEvent(method, path, 0, false); throw ApiError(0, lastErr?.toString() ?? 'request failed'); } Future?> requestList(String path, ListOpts? opts) { final qs = {}; if (opts != null) { if (opts.limit != null) qs['limit'] = opts.limit.toString(); if (opts.offset != null) qs['offset'] = opts.offset.toString(); if (opts.sort != null && opts.sort!.isNotEmpty) qs['sort'] = opts.sort!; if (opts.q != null && opts.q!.isNotEmpty) qs['q'] = opts.q!; if (opts.filters != null) { opts.filters!.forEach((k, v) { if (v != null) qs[k] = v.toString(); }); } } var p = path; if (qs.isNotEmpty) { final encoded = qs.entries.map((e) => '${Uri.encodeQueryComponent(e.key)}=${Uri.encodeQueryComponent(e.value)}' ).join('&'); p = '$p${path.contains('?') ? '&' : '?'}$encoded'; } return requestJson('GET', p, null); } /// Walk the redirect chain manually so Authorization can be dropped /// on cross-origin hops. Caps at 5 hops; mirrors RFC 7231 method /// rewrite semantics. Future<_Response> _sendFollowingRedirects( String method, String urlIn, dynamic body) async { var url = urlIn; var currentMethod = method; dynamic currentBody = body; var stripAuth = false; for (var hop = 0; hop < 5; hop++) { final uri = Uri.parse(url); final req = await _http.openUrl(currentMethod, uri).timeout(_defaultTimeout); req.followRedirects = false; req.headers.set('Accept', 'application/json'); req.headers.set('User-Agent', _userAgent()); req.headers.set('X-Client-Channel', 'client_$language'); req.headers.set('X-Client-Version', clientVersion); req.headers.set('X-Analytics-Device-Id', _deviceId); req.headers.set('X-Analytics-Session-Id', _sessionId); if (!stripAuth && _token.isNotEmpty) { req.headers.set('Authorization', 'Bearer $_token'); } if (currentBody != null && currentMethod != 'GET' && currentMethod != 'HEAD') { req.headers.set('Content-Type', 'application/json'); final encoded = utf8.encode(json.encode(currentBody)); req.contentLength = encoded.length; req.add(encoded); } final resp = await req.close().timeout(_defaultTimeout); final raw = await resp.transform(utf8.decoder).join(); final hmap = {}; resp.headers.forEach((k, v) { hmap[k.toLowerCase()] = v.join(','); }); final status = resp.statusCode; if (status < 300 || status >= 400 || status == 304) { return _Response(status, hmap, raw); } final loc = hmap['location']; if (loc == null || loc.isEmpty) return _Response(status, hmap, raw); Uri nextUri; try { nextUri = uri.resolve(loc); } catch (_) { return _Response(status, hmap, raw); } if (nextUri.origin != uri.origin) stripAuth = true; if (status == 303 || ((status == 301 || status == 302) && currentMethod != 'GET' && currentMethod != 'HEAD')) { currentMethod = 'GET'; currentBody = null; } url = nextUri.toString(); } return _Response(0, const {}, ''); } // ── Analytics ────────────────────────────────────────────────────── void _emitCallEvent(String method, String path, int status, bool ok) { final includeEnv = !_metaSentOnce; _metaSentOnce = true; Future(() async { try { final meta = { 'channel': 'client_$language', 'client_version': clientVersion, 'module_name': moduleName, 'language': language, 'os': Platform.operatingSystem, 'dart_version': Platform.version, }; if (includeEnv) meta['env'] = _fingerprint(); final pathBase = path.split('?').first; final evt = { 'type': 'client.call', 'ts_client': DateTime.now().millisecondsSinceEpoch ~/ 1000, 'meta': { 'method': method.toUpperCase(), 'path': pathBase.length > 128 ? pathBase.substring(0, 128) : pathBase, 'status': status, 'ok': ok, }, }; final payload = json.encode({ 'device_id': _deviceId, 'session_id': _sessionId, 'events': [evt], 'meta': meta, }); final client = HttpClient(); client.connectionTimeout = const Duration(seconds: 2); try { final uri = Uri.parse('$_baseUrl/xapi2/analytics/challenge'); final req = await client.postUrl(uri).timeout(const Duration(seconds: 4)); req.headers.set('Content-Type', 'application/json'); req.headers.set('User-Agent', _userAgent()); final encoded = utf8.encode(payload); req.contentLength = encoded.length; req.add(encoded); final resp = await req.close().timeout(const Duration(seconds: 4)); await resp.drain(); } finally { client.close(force: true); } } catch (_) { /* fire-and-forget */ } }); } // ── Auto-update ──────────────────────────────────────────────────── void _maybeAutoupdate() { if (_autoupdateAttempted) return; _autoupdateAttempted = true; if (!_autoupdateEnabled()) return; Future(() async { try { final d = _stateDir(); if (d == null) return; final stamp = File('$d/update_check.json'); if (stamp.existsSync()) { try { final blob = json.decode(stamp.readAsStringSync()) as Map; final last = blob['checked_at']; if (last is num && (DateTime.now().millisecondsSinceEpoch ~/ 1000) - last.toInt() < 86400) { return; } } catch (_) {} } try { stamp.writeAsStringSync(json.encode({'checked_at': DateTime.now().millisecondsSinceEpoch ~/ 1000})); } catch (_) {} // Source replacement is intentionally a no-op in Dart - users // typically ship AOT-compiled artefacts (Flutter apps, dart // compile exe), so the .dart file on disk is just a record of // the version they vendored. Surface the new version through // the next build. } catch (_) { /* best-effort */ } }); } /// List `log_entry` rows. Future?> logEntryList({ListOpts? opts}) => requestList('/xapi2/data/log_entry', opts); /// Fetch one `log_entry` row by id. Future?> logEntryGet(String id) => requestJson('GET', '/xapi2/data/log_entry/' + id, null); /// Create a new `log_entry` row. Future?> logEntryCreate(Map data) => requestJson('POST', '/xapi2/data/log_entry', data); /// Patch a `log_entry` row. Future?> logEntryUpdate(String id, Map data) => requestJson('PATCH', '/xapi2/data/log_entry/' + id, data); /// Delete a `log_entry` row. Future logEntryDelete(String id) async { await requestJson('DELETE', '/xapi2/data/log_entry/' + id, null); return true; } /// List `sourdough` rows. Future?> sourdoughList({ListOpts? opts}) => requestList('/xapi2/data/sourdough', opts); /// Fetch one `sourdough` row by id. Future?> sourdoughGet(String id) => requestJson('GET', '/xapi2/data/sourdough/' + id, null); /// Create a new `sourdough` row. Future?> sourdoughCreate(Map data) => requestJson('POST', '/xapi2/data/sourdough', data); /// Patch a `sourdough` row. Future?> sourdoughUpdate(String id, Map data) => requestJson('PATCH', '/xapi2/data/sourdough/' + id, data); /// Delete a `sourdough` row. Future sourdoughDelete(String id) async { await requestJson('DELETE', '/xapi2/data/sourdough/' + id, null); return true; } } class _Response { final int status; final Map headers; final String body; const _Response(this.status, this.headers, this.body); }