runScriptSafely<T> function

Future<void> runScriptSafely<T>(
  1. Map<String, dynamic> msg,
  2. Future<T> fn(
    1. GuiSession session,
    2. dynamic args
    )
)

Safe entrypoint wrapper. Always sends a response back to the orchestrator.

The msg map is provided by SapOrchestrator._launch and contains:

  • rootHandle: pre-connected COM root handle (no need to call connect)
  • sessionId: assigned SAP session index
  • args: user-provided arguments
  • replyTo: SendPort to send the result/error
Future<void> getCustomerName(Map<String, dynamic> msg) async {
  await runScriptSafely<String>(msg, (session, args) async {
    session.startTransaction("XD03");
    // ... automation logic ...
    session.endTransaction();
    return "result";
  });
}

Implementation

Future<void> runScriptSafely<T>(
  Map<String, dynamic> msg,
  Future<T> Function(GuiSession session, dynamic args) fn,
) async {
  SendPort? replyTo;
  try {
    replyTo = msg['replyTo'] as SendPort;
    final rootHandle = msg['rootHandle'] as int;
    final sessionId = msg['sessionId'] as int;
    final args = msg['args'];

    final result = await useSapSession<T>(rootHandle, sessionId, (session) async {
      return await fn(session, args);
    });

    replyTo.send(result);
  } catch (e) {
    if (replyTo != null) {
      replyTo.send(Exception('$e'));
    }
  }
}