AstBundle.fromFile constructor

AstBundle.fromFile(
  1. String path
)

Loads a bundle from a file.

Auto-detects the format based on file content magic bytes:

  • ZIP archive (standard .ast files)
  • Gzip-compressed JSON
  • Plain JSON (fallback)

Throws ArgumentD4rtException if the file doesn't exist, is empty, or has an unrecognized format.

Implementation

factory AstBundle.fromFile(String path) {
  final file = File(path);
  if (!file.existsSync()) {
    throw ArgumentD4rtException('Bundle file not found: $path');
  }

  final bytes = file.readAsBytesSync();
  if (bytes.isEmpty) {
    throw ArgumentD4rtException('Bundle file is empty: $path');
  }

  // Auto-detect format from magic bytes
  if (_startsWith(bytes, AstBundleFormat.zipMagicBytes)) {
    return AstBundle.fromZip(bytes);
  }
  if (_startsWith(bytes, AstBundleFormat.gzipMagicBytes)) {
    return AstBundle.fromBytes(bytes);
  }

  // Fallback: try plain JSON
  try {
    final json = jsonDecode(utf8.decode(bytes));
    if (json is Map<String, dynamic>) {
      return AstBundle.fromJson(json);
    }
  } catch (_) {
    // Fall through to error
  }

  throw ArgumentD4rtException('Unrecognized bundle format in file: $path');
}