import 'dart:convert'; import 'dart:ffi'; import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; import 'package:ffi/ffi.dart'; String _defaultLibrary() { if (Platform.isMacOS) { final bundled = '${File(Platform.resolvedExecutable).parent.parent.path}/Frameworks/libmeshport_ffi.dylib'; if (File(bundled).existsSync()) return bundled; } return Platform.isWindows ? 'meshport_ffi.dll' : Platform.isMacOS ? 'libmeshport_ffi.dylib' : 'libmeshport_ffi.so'; } DynamicLibrary _open(String path) => Platform.isIOS ? DynamicLibrary.process() : DynamicLibrary.open(path); Map _call(String path, int handle, String request) { final library = _open(path); final call = library .lookupFunction< Pointer Function(Uint64, Pointer), Pointer Function(int, Pointer) >('meshport_call'); final free = library .lookupFunction< Void Function(Pointer), void Function(Pointer) >('meshport_string_free'); final input = request.toNativeUtf8(); try { final result = call(handle, input); if (result == nullptr) throw StateError('Native response is null'); try { return jsonDecode(result.toDartString()) as Map; } finally { free(result); } } finally { calloc.free(input); } } class MeshPortClient { final String libraryPath; final int _handle; final Future> Function(Map)? _transport; final Future Function()? _closeTransport; bool _closed = false; MeshPortClient._(this.libraryPath, this._handle) : _transport = null, _closeTransport = null; /// A platform-owned control transport. Responses use the same ABI JSON envelope. MeshPortClient.fromTransport({ required Future> Function(Map) request, required Future Function() close, }) : libraryPath = '', _handle = 0, _transport = request, _closeTransport = close; static Future open({String? libraryPath}) async { final path = libraryPath ?? _defaultLibrary(); final handle = await Isolate.run(() { final lib = _open(path); final version = lib.lookupFunction( 'meshport_abi_version', )(); if (version != 1) throw StateError('Unsupported MeshPort ABI: $version'); return lib.lookupFunction( 'meshport_context_new', )(); }); if (handle == 0) throw StateError('Could not create MeshPort context'); return MeshPortClient._(path, handle); } Future> request(Map request) async { if (_closed) throw StateError('MeshPort context is closed'); final path = libraryPath, handle = _handle, text = jsonEncode(request); final response = _transport != null ? await _transport(request) : await Isolate.run(() => _call(path, handle, text)); if (response['ok'] != true) throw StateError( response['error'] as String? ?? 'Native operation failed', ); return response['data'] as Map; } Future validate(String toml) async { await request({'op': 'validate', 'toml': toml}); } Future start(String toml) async { await request({'op': 'start', 'toml': toml}); } Future stop() async { await request({'op': 'stop'}); } /// Opt in to bounded process-wide punch tracing. Does not replace host logging. Future> enableDiagnostics() => request({'op': 'diagnostics_enable'}); Future> status() => request({'op': 'status'}); Future> probe( String target, { bool udp = false, bool echo = false, int timeoutMs = 5000, }) => request({ 'op': 'probe', 'target': target, 'protocol': udp ? 'UDP' : 'TCP', 'echo': echo, 'timeout_ms': timeoutMs, }); Future connectTcp(String target) async => (await request({'op': 'tcp_connect', 'target': target}))['resource'] as int; Future writeTcp(int stream, Uint8List data) async { await request({ 'op': 'tcp_write', 'resource': stream, 'bytes': data.toList(), }); } Future readTcp(int stream, {int maxBytes = 16384}) async => Uint8List.fromList( List.from( (await request({ 'op': 'tcp_read', 'resource': stream, 'max_bytes': maxBytes, }))['bytes'], ), ); Future bindUdp({int port = 0}) async => (await request({'op': 'udp_bind', 'port': port}))['resource'] as int; Future sendUdp(int socket, String target, Uint8List data) async { await request({ 'op': 'udp_send', 'resource': socket, 'target': target, 'bytes': data.toList(), }); } Future> sampleUdpQuality( int socket, String target, int sequence, { int timeoutMs = 1000, }) => request({ 'op': 'quality_sample', 'resource': socket, 'target': target, 'sequence': sequence, 'timeout_ms': timeoutMs, }); Future> receiveUdp(int socket) => request({'op': 'udp_receive', 'resource': socket}); Future closeResource(int resource) async { await request({'op': 'resource_close', 'resource': resource}); } Future close() async { if (_closed) return; _closed = true; if (_closeTransport != null) { await _closeTransport(); return; } final path = libraryPath, handle = _handle; await Isolate.run( () => _open(path).lookupFunction( 'meshport_context_free', )(handle), ); } }