# Flutter API Reference

## WarpLink

The main entry point. Exported from `package:warplink_flutter/warplink_flutter.dart`.

```dart
import 'package:warplink_flutter/warplink_flutter.dart';
```

`WarpLink` is an abstract final class with static members. There is nothing to instantiate. Every method runs in the root isolate and works on iOS and Android only. On any other platform a call throws an `UnsupportedError`.

### configure

```dart
static Future<void> configure({
  required String apiKey,
  String apiEndpoint = defaultApiEndpoint,
  bool debugLogging = false,
  List<String> linkDomains = const <String>[],
  bool automaticDeepLinks = true,
  bool automaticDeferredDeepLinks = true,
  WarpLinkListener? onLink,
})
```

Initialize the SDK. The key format is validated in Dart; the returned future completes when native configuration completes. It does not wait for the first cold-start or deferred delivery, which arrive in `onLink` right after.

| Parameter | Type | Description |
|-----------|------|-------------|
| `apiKey` | `String` | Your SDK key, created under **Keys** > **SDK keys** in the dashboard. It starts with `wl_live_` for release builds or `wl_test_` for debug builds. |
| `apiEndpoint` | `String` | API base URL. Default: `https://api.warplink.app/v1`. |
| `debugLogging` | `bool` | Native console logging. Default: `false`. |
| `linkDomains` | `List<String>` | Hosts you serve links from, in addition to `aplnk.to`. Default: empty. |
| `automaticDeepLinks` | `bool` | Deliver cold-start and warm-start links to `onLink`. Only takes effect when `onLink` is set. Default: `true`. |
| `automaticDeferredDeepLinks` | `bool` | Run the deferred check from `configure`, with or without `onLink`. Default: `true`. |
| `onLink` | `WarpLinkListener?` | Single sink for cold-start, warm-start, and deferred links, and for configuration failures. |

When `onLink` is set, `configure` wires the launch link, later links, and the deferred check into that one callback. Disambiguate the deferred case with `isDeferred`. Calling `configure` again replaces the earlier configuration and callback.

**A malformed key never throws.** The SDK logs a warning, delivers an `ErrorEvent` carrying a `WarpLinkInvalidApiKeyFormatException` (`E_INVALID_API_KEY_FORMAT`) to `onLink`, and stays unconfigured. iOS and Android behave the same way. A native configuration failure also reaches `onLink` as an `ErrorEvent`. Without `onLink`, that failure completes the returned future with a `WarpLinkException`.

### handleDeepLink

```dart
static Future<WarpLinkDeepLink?> handleDeepLink(String url)
```

Resolve a deep link URL to its link data. This is a manual call and is never superseded by an automatic tap.

**Errors:** `E_NOT_CONFIGURED`, `E_INVALID_URL`, `E_LINK_NOT_FOUND`, `E_PASSWORD_REQUIRED`, `E_NETWORK_ERROR`, `E_SERVER_ERROR`, `E_INVALID_API_KEY`, `E_DECODING_ERROR`

### checkDeferredDeepLink

```dart
static Future<WarpLinkDeepLink?> checkDeferredDeepLink()
```

Check for a deferred deep link on first launch. Returns `null` for a confirmed no-match. Once attribution completed, every call returns the stored result.

"First launch" means the first launch of the current install. A reinstall is a new install and runs the check again, with `is_reinstall` set on the request. See [App Reinstall](https://warplink.app/docs/sdks/flutter/deferred#app-reinstall).

**Errors:** `E_NOT_CONFIGURED`, `E_NETWORK_ERROR`, `E_SERVER_ERROR`, `E_INVALID_API_KEY`, `E_DECODING_ERROR`

### getAttributionResult

```dart
static Future<AttributionResult?> getAttributionResult()
```

Get the stored install attribution result. Returns `null` if the install had no match. Throws `WarpLinkNotConfiguredException` before `configure`.

### redeemInvitation

```dart
static Future<WarpLinkDeepLink?> redeemInvitation(String pastedText)
```

Redeem a referral invitation the person pasted. The SDK never reads the clipboard: the text reaches it only through this call.

Returns the matched link, also cached as the attribution result. Returns `null` when the text is not an invitation or matched nothing; nothing is confirmed then. An invitation that is invalid or expired throws a `WarpLinkServerException` whose message says how to open the link again. After a `WarpLinkNetworkException` the native SDK keeps the invitation and tries again on a later launch, a bounded number of times. That later result is delivered through `getAttributionResult()` and `claimReferral`, not through `onLink`.

**Errors:** `E_NOT_CONFIGURED`, `E_NETWORK_ERROR`, `E_SERVER_ERROR`

### claimReferral

```dart
static Future<ReferralClaimResult> claimReferral(String installerId)
```

Credit the referral behind this install to the person who just signed up. `installerId` is your own stable id for them, 1 to 128 characters. The call is safe to repeat: the same id gets the same answer and is never credited twice. A status of `ReferralClaimStatus.none` is an ordinary answer, not an error.

| Property | Type | Description |
|----------|------|-------------|
| `status` | `ReferralClaimStatus` | `claimed`, `flagged`, `ignored` or `none`. |
| `referralId` | `String?` | The referral's id. `null` for `none`. |
| `linkId`, `linkUrl` | `String?` | The link the referral came from. |
| `matchMethod` | `MatchMethod?` | How the referral was matched. |
| `isExact` | `bool` | `true` when the match rests on exact evidence. |
| `matchConfidence` | `double?` | The confidence of an estimated match. |
| `flags` | `List<String>` | Reasons for review, for example `outside_window`. |
| `duplicateOf` | `String?` | For `ignored`, the referral that holds the credit. |
| `updated` | `bool` | `true` when this call replaced an estimate with an exact match. |
| `replayState` | `ReplayState?` | `original` or `replayed`. |

**Errors:** `E_NOT_CONFIGURED`, `E_NETWORK_ERROR`, `E_SERVER_ERROR`, `E_INVALID_API_KEY`. An empty or over-long `installerId` throws `WarpLinkServerException`.

### clearAttribution

```dart
static Future<void> clearAttribution()
```

Forgets this install's attribution so you can test a first launch again without deleting the app: the cached match, the attempt and completed markers, and any held referral invitation. Only the device is cleared. Server records are not deleted.

Test only. With a `wl_live_` key this does nothing and completes, so it never erases a live install's attribution. With a `wl_test_` key and `automaticDeferredDeepLinks` on, a check in flight is discarded and a new check starts. A match from it reaches `onLink`.

**Errors:** `E_NOT_CONFIGURED` before `configure`. `E_DECODING_ERROR` (`WarpLinkDecodingException`) with the message "Could not clear stored attribution data." when a stored item could not be deleted and some state may remain. Calling again is safe.

### isConfigured

```dart
static Future<bool> isConfigured()
```

Check whether `configure` succeeded. Returns `false` after a rejected key format.

### sdkVersion

```dart
static Future<String> sdkVersion()
```

Returns the version of the **native** WarpLink SDK the app is actually running, not the `warplink_flutter` package version. This is the version sent on the wire. The plugin pins its native dependencies (the `app.warplink:sdk` dependency in the Android module, and a Swift Package Manager requirement for iOS), so asking the native side directly returns the exact version your app runs.

```dart
debugPrint(await WarpLink.sdkVersion()); // the native SDK version
```

### isAttributionComplete

```dart
static Future<bool> isAttributionComplete()
```

Whether the deferred attribution check has definitively completed for the current install. Scoped to one install: it reads `false` again after the app is deleted and reinstalled, or restored from a device backup, because a reinstall is attributed again from scratch. It is useful for diagnostics, or for a host that drives `checkDeferredDeepLink()` manually with `automaticDeferredDeepLinks: false`.

### isWarpLinkUrl

```dart
static Future<bool> isWarpLinkUrl(String url)
```

Whether the URL belongs to a known WarpLink domain. Never throws for a bad URL: an unparsable string returns `false`.

### onDeepLink

```dart
static Stream<WarpLinkEvent> get onDeepLink
```

Every URL the host app receives, resolved, for manual wiring. Emits a `LinkEvent` for a WarpLink link and an `ErrorEvent` for a failure, including `WarpLinkInvalidUrlException` for a foreign URL. Events are not deduplicated and are independent of `onLink`. Cancel the subscription to stop listening.

### getInitialDeepLink

```dart
static Future<WarpLinkDeepLink?> getInitialDeepLink()
```

Takes the URL that launched the app, once, and resolves it. The second call returns `null`. With `automaticDeepLinks` and an `onLink` callback, the launch link goes to `onLink` and this returns `null`.

---

## Types

### WarpLinkListener

```dart
typedef WarpLinkListener = void Function(WarpLinkEvent event);
```

### WarpLinkEvent

A sealed class with two subclasses. Use a `switch` to handle both.

```dart
sealed class WarpLinkEvent {}

final class LinkEvent extends WarpLinkEvent {
  final WarpLinkDeepLink deepLink;
}

final class ErrorEvent extends WarpLinkEvent {
  final WarpLinkException error;
}
```

### WarpLinkDeepLink

```dart
final class WarpLinkDeepLink {
  final String linkId;
  final String destination;
  final String? deepLinkUrl;
  final Map<String, Object?> customParams;
  final bool isDeferred;
  final MatchType? matchType;
  final double? matchConfidence;
  final bool matchGuaranteed;
  final String? attributionId;
  final MatchMethod? matchMethod;
  final EvidenceClass? evidenceClass;
  final ReplayState? replayState;
  final Map<String, Object?> capturedParams;
  final String? tappedAt;
}
```

`customParams` values are JSON values. `deepLinkUrl` is the in-app URL for the current platform, or `null` when the link has none. An absent `matchGuaranteed` reads as `false`, so a probabilistic match never looks guaranteed.

### AttributionResult

```dart
final class AttributionResult {
  final String linkId;
  final MatchType matchType;
  final double matchConfidence;
  final bool matchGuaranteed;
  final bool isDeferred;
  final String? attributionId;
  final MatchMethod? matchMethod;
  final EvidenceClass? evidenceClass;
  final ReplayState? replayState;
  final Map<String, Object?> capturedParams;
  final String? tappedAt;
}
```

The evidence fields use `MatchMethod` (`installToken`, `androidReferrer`, `deviceId`, `linkOpen`, `probabilistic`), `EvidenceClass` (`exact`, `estimated`, `legacyLink`) and `ReplayState` (`original`, `replayed`). A value this SDK does not know reads as `null`, and `null` is never read as exact. `capturedParams` is empty when there are none.

### MatchType

```dart
enum MatchType { deterministic, probabilistic }
```

---

## Error Types

### WarpLinkException

The base type of every error the SDK reports. It is a sealed class, so a `switch` over its subclasses is exhaustive.

```dart
sealed class WarpLinkException implements Exception {
  final String message;
  WarpLinkErrorCode get code;
  String get wireCode; // for example "E_NETWORK_ERROR"
}
```

| Subclass | Code | Description |
|----------|------|-------------|
| `WarpLinkNotConfiguredException` | `E_NOT_CONFIGURED` | SDK not initialized. |
| `WarpLinkInvalidApiKeyFormatException` | `E_INVALID_API_KEY_FORMAT` | Key format invalid. |
| `WarpLinkInvalidApiKeyException` | `E_INVALID_API_KEY` | Key rejected by server. |
| `WarpLinkNetworkException` | `E_NETWORK_ERROR` | Network unreachable or timeout. |
| `WarpLinkServerException` | `E_SERVER_ERROR` | Server returned 5xx, or the failure is unknown. Exposes `statusCode` when known. |
| `WarpLinkInvalidUrlException` | `E_INVALID_URL` | Not a recognized WarpLink domain. |
| `WarpLinkLinkNotFoundException` | `E_LINK_NOT_FOUND` | Link not found or inactive. |
| `WarpLinkPasswordRequiredException` | `E_PASSWORD_REQUIRED` | Link is password protected, so it resolves to no destination and no platform URLs. Open the short URL in a browser, where the password form lives. |
| `WarpLinkDecodingException` | `E_DECODING_ERROR` | Malformed server response. `clearAttribution()` also throws it, with the message "Could not clear stored attribution data.", when a stored item could not be deleted. |

### WarpLinkErrorCode

An enum with one value per code: `notConfigured`, `invalidApiKeyFormat`, `invalidApiKey`, `networkError`, `serverError`, `invalidUrl`, `linkNotFound`, `passwordRequired`, and `decodingError`. Each carries its `wireCode`, the `E_*` string used by the other SDKs.

---

## Native Plugin

`warplink_flutter` is a platform-channel plugin over the native WarpLink iOS and Android SDKs. A method channel carries the calls and two event channels carry links, so every method and type on this page behaves the same on both platforms.

Two properties of the plugin shape are worth knowing when debugging:

- Every future-returning method here makes one native call and completes or throws from its answer. None of them poll.
- `onDeepLink` and the automatic `onLink` sink are independent. The stream reports each URL the app receives.

## Platform Requirements

```yaml
environment:
  sdk: ^3.10.0
  flutter: '>=3.38.0'
```

The native side has its own floor: iOS 15.0 and Android API 26 / Android 8.0 (`minSdk`), matching the standalone iOS and Android SDKs exactly, since this package wraps them rather than reimplementing anything. Set `minSdk = 26` in your app's `android/app/build.gradle.kts`.

### Dart Types Exported

Every type in this reference is exported from the package root:

```dart
import 'package:warplink_flutter/warplink_flutter.dart';
// WarpLink, WarpLinkDeepLink, AttributionResult, MatchType,
// ReferralClaimResult, ReferralClaimStatus, MatchMethod,
// EvidenceClass, ReplayState, AttributionEvidence,
// WarpLinkEvent, LinkEvent, ErrorEvent, WarpLinkListener,
// WarpLinkException (and its subclasses), WarpLinkErrorCode,
// defaultApiEndpoint, warplinkFlutterVersion
```

Importing from an internal path such as `package:warplink_flutter/src/warplink.dart` is unsupported and will break on a future release.

## Troubleshooting

**A method call hangs instead of completing or throwing.** Every method here completes from a single native call. Enable `debugLogging: true` in `configure()` and check the platform console (Xcode for iOS, Logcat filtered to `WarpLink` for Android) for whether the native SDK logged a request at all.

**`customParams` values come back as `Object?` and the analyzer complains.** This is deliberate. Custom parameters are the query parameters of the link's destination URL, returned as a JSON object, so the type is `Map<String, Object?>` rather than a link-specific shape the SDK cannot know ahead of time. Narrow with a cast or a pattern at the call site: `link.customParams['product_id'] as String?`.

**`sdkVersion()` reports a different version than the pub.dev package.** The method reports the native SDK the app runs. Check `android/build.gradle.kts` in the installed package for the `app.warplink:sdk:` version and the Swift package requirement for iOS.

**Handling exceptions inside `onLink`.** `onLink` runs for each streamed event in the listener zone, so an exception thrown from your callback for a streamed event surfaces as an uncaught error there, not from the `configure()` future. Catch inside the callback. The `onLink` call for a malformed key or a native configure error runs inline, so an exception there propagates out of the `configure()` future.

## FAQ

**Does `configure()` need to be awaited before calling other methods?** Only before you call other methods. Link delivery to `onLink` needs no await. Methods called before `configure` succeeds throw `WarpLinkNotConfiguredException`, so await `configure()` first when the next line calls one.

**How do I use WarpLink with a provider or state manager?** The package exports a single static `WarpLink` class with future-returning methods and a stream (`onDeepLink`), the same shape on every platform it supports. Wrap it in your own provider if your codebase prefers that pattern.

**Does `getAttributionResult()` make a network call, or read a stored value?** It reads the native SDK's stored result from the deferred check that already ran; it does not trigger a new attribution request. Call `checkDeferredDeepLink()` if you need to force the check to run (only meaningful before it has completed for the current install).

**Can I call WarpLink from a background isolate?** No. Every method runs in the root isolate. Call `configure()` from `main()` in the root isolate.
