Connect SDK

API reference

A compact reference for the public @mdbase/connect browser SDK, transport-neutral collection client, errors, and helper functions.

MdbaseConnect constructor

Signature
new MdbaseConnect<Frontmatter>({
  serverUrl: string,
  manifest?: MdbaseAppManifest | string,
  redirectUri?: string,
  storage?: Storage,
  relayEncryption?: "required" | "disabled",
  keyStore?: GrantKeyStore,
  directAccess?: "auto" | "disabled",
  loopbackUrl?: string,
  navigate?: (url: string) => void | Promise<void>
})
OptionDefaultPurpose
serverUrlRequiredConnect control-plane origin
manifestNoneBundled manifest object or app-local URL
redirectUriCurrent page for web; unused for portable filesExact callback listed in a web or native manifest
storagelocalStorage for web; memory for opaque portable filesAuthorization credential boundary
relayEncryptionrequiredAllow plaintext relay only in an intentional development environment
keyStoreIndexedDB for web; memory for opaque portable filesOverride encrypted grant key persistence
directAccessautoPrefer the same-computer connector
loopbackUrlFixed connector endpointDevelopment and automated-test override
navigatelocation.assignOpen authorization, including in a native system browser

Runtime environment

environment() returns the effective distribution, applicationOrigin, and credentialStorage. Portable files report origin null and default to memory. A caller-supplied storage or key adapter reports custom.

Registration and authorization

MethodResultPurpose
register()Promise<Application>Load, canonicalize, and register the bundled manifest
authorize(options?)Promise<MdbaseAuthorizationResult>Navigate for web/native, or resolve after short-code approval for portable files
completeAuthorization(callbackUrl?)MdbaseAuthorizationResultComplete a web or native callback and return its bound connection
connections()MdbaseConnectionInfo[]List every saved collection authorization for this application
connection(collectionId)MdbaseConnection | nullResolve one permanently collection-bound client
onConnectionsChange(listener)Unsubscribe functionObserve additions, removal, refresh, and cross-tab storage changes
forgetAll()voidForget every locally retained connection for this application

Portable authorization options

authorize() accepts onDeviceCode to report userCode, verificationUri, verificationUriComplete, expiresAt, and intervalSeconds. Supply openVerification to own the approval window, or an AbortSignal to cancel polling and discard the unapproved key.

MdbaseBrowserLocation

Browser application boundary
const collectionLocation =
  new MdbaseBrowserLocation(manager, {
    collectionParameter: "collection",
    fallbackPath: "/"
  });

Keep one location helper beside the application's stable MdbaseConnect manager. It treats the explicit URL identity as authoritative and selects a saved fallback only when exactly one connection exists.

MethodPurpose
selectedCollectionId()Read the explicit bookmark identity, including one that is not currently authorized
activeConnection()Resolve the bookmarked connection or the sole saved fallback
selectConnection(id, options?)Push or replace a cleaned bookmark URL
authorizationReturnTo()Return the current app-local path after removing temporary OAuth parameters
completeAuthorization(callbackUrl?)Complete PKCE and restore a safe same-origin URL for the approved collection
isAuthorizationCallback(url)Recognize browser and native callback URLs with an authorization result
clearAuthorizationCallback(returnTo?)Remove callback parameters after denial or failure
onChange(listener)Observe saved-connection changes plus browser back and forward navigation
Collection IDs are bookmark-safe locators.

They may appear in history, logs, and shared URLs. They do not authorize an operation. Connect still requires the application's stored grant and enforces it at the collection authority.

Collection operations

The methods below belong to MdbaseConnection, not the manager. A repository that holds one connection cannot accidentally read or write a different collection when the user changes another part of the UI.

MethodRequired operationNotes
describe()describeTypes, contracts, schemas, settings, and supported operations
changes(input?)changesOne resumable cursor page
watch(options?)changesAsync iterator with retry and reset status
read({ path })readEffective and raw frontmatter plus revision
query(input?)queryOne query page
queryPages(input?, options?)querySnapshot-consistent async pages
queryAll(input?, options?)queryLoad every page into one result
create(input)createTyped frontmatter and optional body
update(input)updateCanonical patch and optional revision
preflightRename(input)renameRead-only reference impact
rename(input)renameMove with optional reference updates
renameWithProgress(input, options)renamePreflight reuse, cancellation, and outcome recovery
preflightDelete(input)deleteRead-only backlink impact
delete(input)deleteDelete with optional backlink check
deleteWithProgress(input, options)deletePreflight reuse, cancellation, and outcome recovery
validate(input?)validateCanonical collection validation envelope

Saved views and type source

Saved view methods are listViews(),executeView(), readViewSource(),createViewSource(), updateViewSource(), and deleteViewSource(). Type source methods are readType(), createType(), and updateType(). Updates require the source revision.

Notifications and timers

MethodPurpose
registerNotifications(options)Register Web Push and select declared criteria
unregisterNotifications(worker)Remove the server channel, then unsubscribe the browser
registerNativeNotifications(options)Register or rotate one FCM token
unregisterNativeNotifications()Remove the native channel before deleting its token
listTimers(namespace)Read timers within this grant namespace
putTimer(input)Create or replace one generation-fenced timer
cancelTimer(input)Cancel one timer
reconcileTimers(input)Atomically project the complete desired timer set

Connection, routing, and sync

MethodPurpose
info()Read collection ID, display name, operations, scope, route, and direct status
authorizationCapabilities(required)Compare required and granted operations for this collection
hasOperations(required)Check an operation subset
requestOperations(required, options?)Request the least-privilege union for this same collection
forget()Forget only this locally retained connection
onConnectionChange(listener)Subscribe and receive an unsubscribe function
checkDirectAccess()Read same-computer availability silently
requestDirectAccess()Prompt from a user gesture where required
disableDirectAccess()Persist a relay-only preference for this app
sync()Return one credential-hiding sync transport for a remote, direct, or relayed authority, or null
pendingMutation()Inspect an interrupted encrypted mutation
resumePendingMutation()Recover its exact durable connector receipt

MdbaseCollectionClient

Construct with any MdbaseCollectionTransport. It exposes the record, query, view, type, validation, and timer methods above. Its surface is limited to collection behavior. Domain packages should prefer this dependency when they use collection operations alone.

Errors and helpers

errors.ts
try {
  const result = unwrapOperation(await connection.update(input));
} catch (error) {
  if (error instanceof MdbaseOperationValidationError) {
    renderDiagnostics(error.diagnostics);
  } else if (error instanceof MdbaseConnectError) {
    renderTransportError(error.code, error.recovery);
  }
}
ExportPurpose
unwrapOperation()Return a valid result or throw validation diagnostics
MdbaseConnectErrorTransport, authorization, routing, and request errors with recovery metadata
MdbaseOperationValidationErrorInvalid canonical operation envelope
isRetryableConnectError()Classify transient Connect failures
parseMdbasePushPayload()Validate a browser push envelope
parseMdbaseNativeNotificationData()Validate string-valued FCM/APNs data
showMdbasePushNotification()Validate and display static manifest presentation