stripSharedSwiftPreamble function

String stripSharedSwiftPreamble(
  1. String content
)

Strips the shared public type declarations from a Swift bridge file's content.

When multiple Nitro specs are compiled into the same Swift module, each generated *.bridge.g.swift contains identical declarations for shared types (NitroEncodable, NitroNullableInt, NitroRecordWriter, etc.). Having these in more than one file causes "invalid redeclaration" errors.

This function keeps the file-private string helpers (lines before public protocol NitroEncodable) and the spec-specific protocol + bridge stubs (everything from the first /** doc-comment onward), but drops the shared-type block in between.

The first bridge file in the module should NOT be stripped — it provides the shared types for the entire module. Only 2nd and subsequent files need this treatment.

Safe to apply when no shared block is present (e.g. already stripped or a file that never had it): returns content unchanged.

Implementation

String stripSharedSwiftPreamble(String content) {
  final lines = content.split('\n');
  final result = <String>[];
  var inSharedBlock = false;

  for (final line in lines) {
    if (!inSharedBlock && line.startsWith('public protocol NitroEncodable')) {
      inSharedBlock = true;
      continue;
    }
    if (inSharedBlock) {
      // Resume at the `/**` doc-comment that precedes the spec-specific protocol.
      if (line.startsWith('/**')) {
        inSharedBlock = false;
        result.add(line);
      }
      continue;
    }
    result.add(line);
  }

  return result.join('\n');
}