Skip to content

About

A lightweight, pure Dart deep link routing library

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

17 Commits

Folders and files

Repository files navigation

Dart SDK style: lints

A lightweight, pure Dart deep link routing library. Every link — external (custom schemes, universal links) or internal (in-app HTTP links, web-view redirects) — is routed to a destination class (one class per link) that handles navigation with whatever the app uses (Flutter Navigator, go_router, ...), and OS-bound links (mailto:, sms:, tel:, foreign http) are handed to an injected launcher. All through an onion-style middleware pipeline.

Zero third-party dependencies.


Architecture Overview

deeplinkify architecture

Key Features

  • Three routing flows, one table: external → internal (OS deep links), internal → internal (in-app HTTP links map to internal routes instead of opening a browser), and internal → external (see below).
  • One class per link: extend DeepLinkDestination, declare the link shape in the super constructor, and handle navigation yourself (Flutter Navigator, go_router, or the OS launcher).
  • Internal → external: mailto: / sms: / tel: and foreign http(s) links are handed to an injected ExternalLauncher (mail client, dialer, browser).
  • HTTP identity via settings / .env: LinkIdentity decides which hosts are "this system" (route internally) vs foreign (open browser), fed from your configuration (DEEPLINK_INTERNAL_HOSTS=shop.example.com). It also auto-decides a link's DeepLinkSource whenever you call navigate without one.
  • Declarative destinations: a DeepLinkDestination class declares schemes, hosts, a PathPattern (/product/:id, /docs/*), and allowed sources.
  • Router vocabulary, CQRS structure: DeepLinkRegistry (routing table / resolution) + DeepLinkRouter (orchestration), mirroring the cqrs-dart conventions.
  • Middleware pipeline: onion-style interceptors for logging, auth guards, deep-link queuing, ...
  • Lifecycle observers: onRouted / onLaunched / onFailed for telemetry and UI state.
  • Fail loudly: explicit exceptions (UnresolvedDeepLinkException, DuplicateDestinationException, MalformedPathPatternException, ...).

Quick Start

dependencies:
  deeplinkify: ^0.2.0

1. One class per link

import 'package:deeplinkify/deeplinkify.dart';

/// A destination IS the handler: it declares its link shape and navigates.
class ProductLink extends DeepLinkDestination {
  ProductLink(this.navigator)
      : super(
          schemes: ['https', 'http'],
          hosts: ['shop.example.com'],
          path: '/product/:id',
        );

  final Navigator navigator; // your navigator (Flutter, go_router, ...)

  @override
  Future<void> execute(DeepLinkContext context) async {
    navigator.push(ProductPage(productId: context.params['id']!));
  }
}

2. Register destinations

final router = DeepLinkRouter(
  middlewares: [loggingMiddleware],
  externalLauncher: launchUrl, // your url_launcher wrapper
  identity: LinkIdentity.fromHostsCsv(
    // dart:io Platform.environment — VM/CLI only; see "HTTP Identity".
    Platform.environment['DEEPLINK_INTERNAL_HOSTS'] ?? '',
  ),
);

identity is required: every unmatched link and every navigate call without an explicit source is decided through it — see "HTTP Identity" below.

// The whole link surface, in one place. The destination name defaults to
// the class name, so one registration line per link is enough.
router.registry
  ..register(ProductLink(navigator))      // https://shop.example.com/product/:id
  ..register(HomeLink(navigator))         // myapp://app/home
  ..register(MailLink());                 // mailto:... -> OS

3. Route

// External: handed in by the operating system. `source` must be explicit
// here — identity can't tell an OS-delivered universal link from an
// in-app tap of the same URL, and CheckoutLink-style destinations rely on
// that distinction (see "Source-Aware Destinations").
await router.navigate('myapp://app/product/42',
    source: DeepLinkSource.external);

// Internal-to-internal: the same HTTP link tapped inside the app becomes
// the internal route — no browser, no web-view redirect.
await router.navigate('https://shop.example.com/product/7',
    source: DeepLinkSource.internal);

// Internal-to-external: OS-handled schemes and foreign http(s) links leave
// the app through the external launcher.
await router.navigate('mailto:hello@shop.example.com',
    source: DeepLinkSource.internal);
await router.navigate('https://news.example.com/top-story',
    source: DeepLinkSource.internal); // foreign host -> browser

// No opinion on the source? Leave it unset and `identity` decides from
// the link itself (internal host / non-escape-list scheme -> internal;
// foreign host or mailto:/sms:/tel: -> external).
await router.navigate('https://shop.example.com/product/9');

Every routed link ends at the matched destination class's execute, which receives a DeepLinkContext with captured params, query parameters, and the uri — everything needed to navigate.

The Three Flows

Flow Example Outcome
External → internal myapp://app/product/42 (source: external) destination class executes → in-app navigation
Internal → internal https://shop.example.com/product/7 (source: internal) destination class executes — no browser
Internal → external mailto:..., sms:..., tel:... handed to ExternalLauncher (mail/SMS/dialer)
Internal → external https://news.example.com/... (foreign host) handed to ExternalLauncher (browser)

External Destinations & the Launcher

OS-bound links are destination classes whose execute hands the link to the launcher (typically wrapping url_launcher / AppLinks):

class MailLink extends DeepLinkDestination {
  MailLink(this.externalLauncher)
      : super(schemes: ['mailto'], path: '/*'); // the address IS the path

  final ExternalLauncher externalLauncher;

  @override
  Future<void> execute(DeepLinkContext context) =>
      externalLauncher(context.uri);
}

These run through the middleware pipeline like any other link. Links that match no destination at all are handled by the LinkIdentity fallback (see below) and are launched directly.

HTTP Identity: which links are "ours" (LinkIdentity)

identity is a required DeepLinkRouter argument, and does two jobs:

  1. Auto-decides DeepLinkSource. Call navigate / routeUri / route without a source and the router asks identity: internal hosts (and any scheme not in externalSchemes) become DeepLinkSource.internal, everything else becomes DeepLinkSource.external. Pass source explicitly whenever the call site's origin matters more than the link's shape — e.g. telling an OS-delivered universal link apart from an in-app tap of the exact same URL (see "Source-Aware Destinations").
  2. Decides the fallback for unmatched links. For an http(s) link raised inside the app, the router must decide: is this host part of this system (route internally) or foreign (open browser)? That identity comes from your settings — either direct code or an environment variable:
# .env
DEEPLINK_INTERNAL_HOSTS=shop.example.com,www.shop.example.com
// VM / CLI: read the variable directly.
import 'dart:io';

final identity = LinkIdentity.fromHostsCsv(
  Platform.environment['DEEPLINK_INTERNAL_HOSTS'] ?? '',
);

// Or pass hosts inline (Flutter: feed values from --dart-define / dotenv).
final identity = const LinkIdentity(internalHosts: {'shop.example.com'});

Behavior when no destination matches:

Link Disposition
http(s) to an internalHosts host fail loudly (UnresolvedDeepLinkException) — a registration bug
http(s) to a foreign host launched in the browser
mailto: / sms: / tel: (customize via externalSchemes) launched in the OS app
other custom scheme fail loudly (UnresolvedDeepLinkException)

Destinations always win over the fallback. Launching also requires an externalLauncher; without one, a link identity classifies as external fails with MissingExternalLauncherException instead.

Pattern Syntax

Syntax Example Matches
/literal /home /home
/:name /product/:id /product/42 → params['id'] == '42'
/* /docs/* /docs/a/b → wildcard == 'a/b' (must be last)

Matching hooks — override what you need:

Hook Default Override for
transformPath(path) identity remap external paths onto the declared pattern
matchesSource(source) allowedSources contains custom source policy
matchesScheme(scheme) schemes contains (case-insensitive) scheme aliases
matchesHost(host) hosts contains (case-insensitive) subdomain trees
matchIf(link) all of the above, in order wholesale custom strategy (e.g. query-driven matching)

Matching rules:

  • Scheme and host lists are matched case-insensitively; empty lists mean "any".
  • Path segments are case-sensitive; trailing slashes are ignored.
  • Query parameters are available on the match, no need to declare them.
  • Priority: when several destinations match, the highest DeepLinkDestination.priority wins; ties break by registration order.

Custom Matching Per Class

External paths rarely match the internal route shape 1:1 — remap them in the destination class with transformPath:

/// External link: http://demo.somedomain.com/job/post/1
/// Internal shape: /job/:id
class JobLink extends DeepLinkDestination {
  JobLink(this.navigator)
      : super(
          schemes: ['http', 'https'],
          hosts: ['demo.somedomain.com'],
          path: '/job/:id',
        );

  final Navigator navigator;

  @override
  String transformPath(String path) =>
      path.replaceFirst('/job/post/', '/job/');

  @override
  Future<void> execute(DeepLinkContext context) async {
    navigator.push(JobPage(id: context.params['id']!)); // id = '1'
  }
}

The original uri stays untouched on the match — transformPath only shapes what the pattern matches against. For wholesale custom strategies (query-driven matching, legacy scheme aliases, subdomain trees), override matchesSource / matchesScheme / matchesHost or the full matchIf — see the hook table above.

Source-Aware Destinations

Restrict a destination to specific origins with allowedSources:

// Checkout must go through the app UI: an external tap falls through
// (the OS opens the browser), an in-app tap routes internally.
class CheckoutLink extends DeepLinkDestination {
  CheckoutLink(this.navigator)
      : super(
          schemes: ['https', 'http'],
          hosts: ['shop.example.com'],
          path: '/checkout',
          allowedSources: [DeepLinkSource.internal],
        );

  final Navigator navigator;

  @override
  Future<void> execute(DeepLinkContext context) async {
    navigator.push(const CheckoutScreen());
  }
}

Middleware

class LoggingMiddleware implements DeepLinkMiddleware {
  @override
  Future<void> handle(DeepLinkContext context, DeepLinkNextHandler next) async {
    print('routing ${context.link.raw}');
    await next();
    print('done');
  }
}

Not calling next short-circuits the routing (the destination's handle never runs).

Observers

class TelemetryObserver implements DeepLinkObserver {
  @override
  void onRouted(DeepLinkContext context) => /* ... */;

  @override
  void onLaunched(DeepLink link) => /* ... */;

  @override
  void onFailed(DeepLink link, Object error) => /* ... */;
}

router.addObserver(TelemetryObserver());

Failures still propagate: route rethrows after notifying observers.

Exceptions

Exception Raised when
MalformedDeepLinkException link has no scheme / is empty
MalformedPathPatternException destination path pattern is invalid
DuplicateDestinationException a destination name is registered twice (message names both classes)
UnresolvedDeepLinkException no destination matches the link (and identity does not declare it external)
MissingExternalLauncherException an external link must launch but no externalLauncher is configured

Development

dart pub get
dart analyze
dart test
dart run example/deeplinkify_example.dart

About

A lightweight, pure Dart deep link routing library

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages