Skip to main content

mortar_client 0.7.0 copy "mortar_client: ^0.7.0" to clipboard
mortar_client: ^0.7.0 copied to clipboard

Dart and Flutter client for Mortar, a mainland-China-friendly Backend-as-a-Service for mobile and web apps.

mortar_client (Dart / Flutter) #

Dart client for Mortar, a mainland-China-friendly Backend-as-a-Service.

Works in pure Dart, Flutter (iOS / Android / web / macOS / Windows / Linux), and Dart server. Anywhere package:http runs.

Module coverage #

The server's 10-feature inventory defines ownership, not ten properties on every SDK client. The project-scope MortarClient exposes auth, Database through from(...), storage, realtime, functions.invoke, and analytics. Current Analytics HTTP handlers require app/admin scope; the SDK property does not make ingestion available to a PUBLIC bundle key. Never put a privileged key in a mobile or browser bundle.

Provisioning and operator operations remain separate. AccountClient uses an owning-account token for accounts/projects, API keys, top-up, and operator reads (usage, crons, and function logs). Custom Domains is platform management, not an application feature. This native SDK has no dedicated Cronjob, Messaging, Secrets, or Custom Domains management facade; do not invent methods from the feature list. Trusted server code can manage bindings and task attempts through the separate Queues client and atomically enqueue jobs through DatabaseTransactions.

App connection and application-grant ownership belongs to Auth. The opt-in connection/authorization controllers currently live in the TypeScript SDK; there is no corresponding native controller in this SDK.

Use a build matching the deployed /database, /functions, /cronjob, /queues, /messaging, and /auth/apps API contract. Source changes do not prove package publication. Schemas: OpenAPI.

Install #

# pubspec.yaml
dependencies:
  mortar_client: ^0.1.0

Or run dart pub add mortar_client.

Project-scope client #

Password signup is mortar.auth.signUp(username: username, password: password). Passwordless email/phone enrollment uses signInWithOtp(email: email) / (phone: phone), then verifyOtp(email: email, token: code, type: "email") / (phone: phone, token: code, type: "sms"). Email/phone password signup is also supported and follows the confirmation policy. Inputs are preserved, including Unicode and whitespace. See auth boundaries.

import 'package:mortar_client/mortar_client.dart';

final mortar = MortarClient(ClientOptions(
  url: 'https://project-uuid.api.mortar.appunvs.com',
  apiKey: 'mtr_live_xxx',
));

// Database — Supabase-faithful chainable query builder.  Each call is
// awaitable, returns the data directly, and THROWS `MortarApiError` on error
// (the supabase-dart idiom — no `{data, error}` envelope).  Rows are FLAT
// (your fields plus id / created_at / updated_at at the top level).
final todos = await mortar
    .from('todos')
    .select()
    .eq('done', false)
    .order('created_at', ascending: false)
    .limit(50);
final row = await mortar.from('todos').insert({'title': 'buy milk'});
// Batch insert/upsert and filtered update/delete each execute atomically in
// one server-side PostgreSQL transaction:
await mortar.from('todos').update({'title': 'buy milk + eggs'}).eq('id', row['id']);
await mortar.from('todos').delete().eq('id', row['id']);
final one = await mortar.from('todos').select().eq('id', row['id']).single();
// Back-compat by-id forms also still work:
//   mortar.from('todos').getById(id) / updateById(id, data) / deleteById(id)

// End-user auth — Supabase surface (signInWithPassword / signInWithOtp /
// verifyOtp / getUser / getSession / refreshSession / signOut /
// onAuthStateChange / resetPasswordForEmail), all throw + return data directly.
final res = await mortar.auth.signInWithPassword(email: 'alice@example.com', password: '...');
// Later calls on mortar use this session automatically.
mortar.auth.onAuthStateChange((event, session) => print('auth: $event'));
await mortar.auth.signInWithOtp(email: 'alice@example.com');     // send OTP
// final s = await mortar.auth.verifyOtp(email: 'alice@example.com', token: '123456', type: 'email');
final me = await mortar.auth.getUser();          // GET /auth/me
final current = mortar.auth.getSession();         // in-memory session or null
await mortar.auth.resetPasswordForEmail('alice@example.com');
// await mortar.auth.signOut(); // when the user chooses to sign out

// Storage — supabase-dart `storage.from(bucket)` handle
await mortar.storage
    .from('avatars')
    .upload('alice.jpg', await imageFile.readAsBytes(), contentType: 'image/jpeg');
final bytes = await mortar.storage.from('avatars').download('alice.jpg');
final url = await mortar.storage.from('avatars').createSignedUrl('alice.jpg', 3600);

// For media lists, lazy-load visible items and reuse each signed URL until it
// nears expiry. Signing is outside the project API-concurrency budget and is
// not itself an object-egress charge; the URL downloads directly from storage.

// Realtime — supabase `mortar.channel(name)` + `channel.on('postgres_changes', ...)`
final room = mortar.channel('todos-room')
  ..on('postgres_changes', {'event': '*', 'table': 'todos'},
      (p) => print('${p.eventType} ${p.newRecord}'));
room.subscribe();
// later: mortar.removeChannel(room);

// Realtime — low-level SSE subscription to row changes
final sub = mortar.realtime.subscribe(
  'todos',
  (ev) => print('${ev.op} ${ev.id}'),
  onError: (e) => print('realtime err: $e'),
);
// later: sub.unsubscribe();

// Functions — invoke a deployed function
final res = await mortar.functions.invoke(name: 'hello');
print(res.body);

Trusted server code using an app/admin key can combine cross-table row writes and PostgreSQL queue enqueue in one ACID transaction:

final transactions = DatabaseTransactions(ClientOptions(
  url: 'https://project-uuid.api.mortar.appunvs.com',
  apiKey: Platform.environment['MORTAR_APP_KEY']!,
));

await transactions.execute([
  DatabaseTransactionOperation.insert('orders', {'status': 'pending'}),
  DatabaseTransactionOperation.update('inventory', productId, {'stock': 9}),
  DatabaseTransactionOperation.enqueue(
    'send-receipt',
        idempotencyKey: 'receipt-order-1',
    payload: {'order_id': orderId},
  ),
]);

This boundary includes only the same PostgreSQL database. Object storage, external HTTP calls, email delivery, and function execution are not part of the transaction; model those as durable jobs with idempotent workers.

Auth options and sessions #

Supported Auth methods follow the Supabase contract in the language's native return/throw style. Email/phone signup can return a user with a null session; username is an additional immediate-login credential. Do not call password login after successful signup. OTP type is required (email, sms, recovery, email_change, phone_change; email aliases signup, magiclink, invite).

Signup and OTP accept profile data and captchaToken; password and ID-token login accept CAPTCHA, and ID-token login accepts accessToken for at_hash. shouldCreateUser defaults true; SMS channel defaults sms. updateUser accepts password, email, phone and metadata; secure email change confirms both addresses. Metadata does not change database permissions.

Sessions and PKCE verifiers persist by default; inject authStorage for a host store or disable with persistSession. Resource calls automatically use the current session and refresh near expiry. OAuth navigation remains host-owned. signOut defaults to global; local affects this session, others retains it. Inspect thrown errors through status, code, and message, including 400 invalid_credentials, 422 otp_disabled, and 403 otp_expired.

Email signup, OTP, recovery and email changes use PKCE by default. Supply the callback code to exchangeCodeForSession on the same configured store. Automatic refresh is enabled by default; hosts may call stopAutoRefresh / startAutoRefresh for app lifecycle, or set autoRefreshToken false.

final pending = await mortar.auth.signUp(
  email: email, password: password,
  data: {'display_name': 'Member'}, emailRedirectTo: 'myapp://auth/callback',
);
if (pending.session == null) {
  // Show the confirmation prompt; wait for the email link or OTP.
}
await mortar.auth.signInWithOtp(email: email, shouldCreateUser: false);
// Email callback: await mortar.auth.exchangeCodeForSession(code);
await mortar.auth.updateUser(data: {'display_name': 'Updated', 'old_field': null});
await mortar.auth.signOut(scope: 'others'); // current session remains

Account-scope client #

import 'package:mortar_client/mortar_client.dart';

final account = AccountClient(url: 'https://api.mortar.appunvs.com');
await account.signIn(email: 'me@example.com', password: 'hunter2');

final projects = await account.listProjects();
final created = await account.createProject(name: 'staging', tier: 'mini');
await account.updateProject(created.id, tier: 'small');

// Operator reads (control plane) — usage / crons / function logs
final usage = await account.usage(created.id);
final crons = await account.crons(created.id);
final logs = await account.logs(created.id, 'hello', limit: 100);

await account.deleteProject(created.id);

Errors #

Every method throws MortarApiError on non-2xx.

try {
  await mortar.from('todos').insert({'title': 'x'});
} on MortarApiError catch (e) {
  // Stable fields: code, category, requestId, retryable, retryAfterMs.
  if (e.category == 'quota') {
    // top up, change plan, or wait
  } else {
    // map the category to the app's shared recovery UI
  }
}

functions.invoke returns a tenant Function's 4xx/5xx as http.Response; only a Mortar platform failure throws MortarApiError.

Run tests #

dart pub get
dart test

License #

Apache License 2.0.

Trusted project queues #

Queue management is server-side only. The independent Queues client (Go: TrustedProjectClient queue methods) supports bindings, idempotent enqueue, job/attempt reads, cancellation, and explicit redrive. It is not a property of the public MortarClient; never embed an app/admin key in an application bundle.

Create a binding paused with expected_revision: "0", then explicitly resume using its current revision and a command idempotency key. Default maximum attempts is 3 (at most 5). Every direct or transactional enqueue requires a stable idempotency_key. Automatic retries only cover confirmed pre-dispatch failures; unknown outcomes stop. Explicit redrive creates a new job but retains its execution_key; unknown additionally requires acknowledge_unknown: true after human review. Queue deduplication does not make other database transaction operations idempotent. List dates are RFC3339 creation-time [from, to).

These source changes require coordinated server and consumer adoption. Package publication and deployment remain separate release steps.

Trusted function invocation reads #

Use FunctionObservability.list, get, and logs with server-side project credentials. These are not methods on the public app client. List filters accept RFC3339 [from,to), source (http, cronjob, queue), status, limit and an opaque cursor. Retain filters while paging; the list cursor expires after 15 minutes. Receipt fields http_status and duration_ms are optional, so missing is not zero. Status not_dispatched means tenant code did not start; unknown never authorizes replay.

Associated logs use the persisted invocation ID; the API does not accept an arbitrary provider request ID or client time window. available may contain an empty entries array, while unavailable has a reason such as mapping_missing or provider_unsupported. Provider failures throw the normal API error. query_complete describes the provider query, and truncated reports a bounded result. An empty array with query_complete=false is incomplete, not an empty state; preserve any returned lines and allow a log-only refresh. Log timestamps remain RFC3339 strings. Follow next_cursor with the same page size; a log snapshot lasts 2 minutes and is limited to 1000 entries/1 MiB (16 KiB per line). On 410 cursor_expired, refresh the first page rather than re-invoking. Public invoke preserves its raw response and the protected X-Mortar-Invocation-ID header.

Secret PUT/DELETE success means stored. Secret values remain write-only; metadata lists only names and modification times. An explicitly supplied empty string is valid; omission/null is invalid. Managed FC environment revisions are synchronized in bounded background work and checked before HTTP/Cron/Queue dispatch. Unsupported providers do not silently drop secrets. Existing running instances retain their environment; a save/delete receipt does not prove immediate application/removal on every provider instance.

An uncertain provider configuration write blocks later calls/synchronization and function Deploy/Delete until the exact recorded operation, revision and target is confirmed ready. An older Active configuration or a fixed wait does not prove that write completed. There is no public force-clear API; an unconfirmed write requires an explicit operational resolution based on provider evidence, not automatic replay.

Notion App User connections #

Use mortar.appConnections(publicAppId) after normal App User login. It exposes list/get/reserve, startAuthorization/confirmAuthorization/disconnect, and prepareOperation/getOperationApproval/cancelOperationApproval/executeOperation. Current policy/consent versions, generation and capabilities come from the connection response; read is optional. Do not pass a user ID or provider token.

final connections = mortar.appConnections(publicAppId);
final row = await connections.reserve('notion');
final result = await connections.executeOperation(row.id, AppUserOperation(
  expectedGeneration: row.authorizationGeneration,
  operation: NotionOperation.search,
  arguments: {'query': 'Project notes', 'page_size': 10},
));

Native hosts own external browser launch and the reviewed return mechanism. Validate the pinned Gateway origin and exact operation confirmation path. The confirmation URL has a one-use #handoff=<64 hex>; never log/persist it. OAuth return carries the attempt and one-use nonce. Operation return carries only app_connection_operation and connection_id; clear them before loading app content and use the owner API to fetch approval arguments/generation.

Search/fetch need read. Create/update need write; deletePages moves pages to trash and needs delete. Mutations first call prepareOperation, show the server summary, and navigate to Gateway for user confirmation. A status GET does not execute; only an explicit Execute action sends the exact AppUserOperation with approvalId. Cancel uses cancelOperationApproval. All calls use the current session before dispatch, refuse redirects and never retry; an unknown write outcome requires user-led recovery. Clear all connection/content state on user/app changes. Browser clients that cannot disable redirects fail closed; this API does not implement Flutter Web OAuth UI or native platform handoff.

0
likes
160
points
722
downloads

Documentation

Documentation
API reference

Publisher

verified publisherappunvs.com

Weekly Downloads

Dart and Flutter client for Mortar, a mainland-China-friendly Backend-as-a-Service for mobile and web apps.

Homepage
Repository (GitHub)
View/report issues

Topics

#baas #backend #database #realtime #storage

License

Apache-2.0 (license)

Dependencies

crypto, http

More

Packages that depend on mortar_client