diff --git a/public/examples/sandbox-quickstart.mjs b/public/examples/sandbox-quickstart.mjs
index f186ef4..0fb24c9 100644
--- a/public/examples/sandbox-quickstart.mjs
+++ b/public/examples/sandbox-quickstart.mjs
@@ -1,50 +1,55 @@
-import { unwrapOperation } from "@mdbase/connect";
-import { createSandbox } from "@mdbase/connect-dev";
+import { createSandbox } from "@mdbase-dev/connect-dev";
const { client, transport } = createSandbox({
- records: [
- {
- path: "tasks/first.md",
- types: ["task"],
- frontmatter: {
- type: "task",
- title: "Read the collection",
- completed: false
- }
+ records: [{
+ path: "tasks/first.md",
+ types: ["task"],
+ frontmatter: {
+ type: "task",
+ title: "Read the collection",
+ completed: false
}
- ]
+ }]
});
-const first = unwrapOperation(await client.read({ path: "tasks/first.md" }));
+// Every operation returns a ConnectOutcome: check ok, then use value or problem.
+function required(outcome) {
+ if (!outcome.ok) throw new Error(`${outcome.problem.code}: ${outcome.problem.message}`);
+ return outcome.value;
+}
-const created = unwrapOperation(
- await client.create({
+const first = required(await client.read({ path: "tasks/first.md" }));
+
+const created = required(await client.create({
+ type: "task",
+ path: "tasks/second.md",
+ frontmatter: {
type: "task",
- path: "tasks/second.md",
- frontmatter: {
- type: "task",
- title: "Update one record",
- completed: false
- }
- })
-);
-
-const updated = unwrapOperation(
- await client.update({
- path: created.path,
- patch: { completed: true },
- if_revision: created.revision
- })
-);
-
-const tasks = unwrapOperation(
- await client.query({
- types: ["task"],
- limit: 20
- })
-);
+ title: "Update one record",
+ completed: false
+ }
+}));
+
+const updated = required(await client.update({
+ path: created.path,
+ patch: { completed: true },
+ ifRevision: created.revision
+}));
+
+// Reusing the old revision is refused instead of overwriting the update.
+const stale = await client.update({
+ path: created.path,
+ patch: { completed: false },
+ ifRevision: created.revision
+});
+
+const tasks = required(await client.query({
+ types: ["task"],
+ limit: 20
+}));
console.log(`Read: ${first.frontmatter.title}`);
console.log(`Updated: ${updated.path} (completed: ${updated.frontmatter.completed})`);
+console.log(`Stale revision: ${stale.ok ? "accepted" : stale.problem.code}`);
console.log(`Task records: ${tasks.results.length}`);
console.log(`Markdown paths: ${transport.snapshot().map((record) => record.path).join(", ")}`);
diff --git a/src/pages/sdk/api/index.astro b/src/pages/sdk/api/index.astro
index a5f8e09..c1c755a 100644
--- a/src/pages/sdk/api/index.astro
+++ b/src/pages/sdk/api/index.astro
@@ -3,48 +3,57 @@ import DocsLayout from "../../../components/DocsLayout.astro";
import CodeBlock from "../../../components/CodeBlock.astro";
const constructor = `new MdbaseConnectMdbaseConnect constructor
@@ -103,6 +112,16 @@ const error = `try {
location.assignOpen authorization, including in a native system browser
+
+
+
+ identityStoreIndexedDB
+ Persist the application's signing identity
+
+
@@ -115,7 +134,12 @@ const error = `try {
storage or key adapter reports
+ timeoutsPer workload
+ Default budgets for requests, watch start-up, file indexing, uploads and sync;
+ null disables one deliberatelycustom.
+ Every asynchronous method accepts a final{" "}
+ ConnectRequestOptions argument, with signal and
+ {" "}timeoutMs, and resolves to a ConnectOutcome.
+
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?) |
- MdbaseAuthorizationResult |
- Complete a web or native callback and return its bound connection | -
connections() |
- MdbaseConnectionInfo[] |
- List every saved collection authorization for this application | -
connection(collectionId) |
- MdbaseConnection | null |
- Resolve one permanently collection-bound client | -
onConnectionsChange(listener) |
- Unsubscribe function | -Observe additions, removal, refresh, and cross-tab storage changes | -
forgetAll() |
- void |
- Forget every locally retained connection for this application | -
application(options) | MdbaseApplicationSession | The ordinary application lifecycle entry point |
register(options?) | ConnectOutcome<Application> | Load, canonicalize, and register the bundled manifest |
manifest(options?) | ConnectOutcome<MdbaseApplicationManifest> | The loaded, validated manifest |
authorize(options?) | ConnectOutcome<MdbaseAuthorizationOutcome> | Registry-level authorization; applications normally use the session |
completeAuthorization(callbackUrl?, options?) | ConnectOutcome<MdbaseAuthorizationResult> | Complete a web or native callback |
connections() | MdbaseConnectionInfo[] | Every saved collection authorization for this application |
connection(collectionId) | MdbaseConnection | null | One permanently collection-bound client |
unavailableReason(collectionId) | MdbaseUnavailableReason | null | Why a saved collection cannot be used |
onConnectionsChange(listener) | Unsubscribe function | Observe additions, removal, refresh, and cross-tab storage changes |
environment() | MdbaseConnectEnvironment | Distribution, origin, and credential storage in effect |
forgetAll() | void | Forget every locally retained connection for this application |
- authorize() accepts onDeviceCode to report
+ authorize() on the manager or session accepts
+ {" "}onDeviceCode to report
{" "}userCode, verificationUri,
{" "}verificationUriComplete, expiresAt, and
{" "}intervalSeconds. Supply openVerification to own
@@ -172,27 +173,28 @@ const error = `try {
discard the unapproved key.
- 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.
+ One session owns collection selection, authorization, setup checks, and a
+ snapshot. MdbaseBrowserSelection keeps the selected
+ collection in the URL and follows back and forward navigation; native
+ shells supply their own selection adapter.
| Method | Purpose |
|---|---|
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 |
start(options?) | Load the manifest and restore the selected collection; concurrent callers share the work |
subscribe(listener), getSnapshot() | External-store state: unselected, authorization_required, checking_setup, setup_review_required, ready, unavailable, blocked, and start-up states |
connection() | The ready collection's MdbaseConnection, or null |
authorize(target, options?) | Authorize "choose", "selected", or {`{ collectionId }`} |
completeAuthorization(callbackUrl?, options?) | Complete the callback; the snapshot becomes ready |
ensureCapabilities(capabilities, options?) | Request declared optional capabilities; unchanged when already granted |
applyCollectionSetup(options?) | Apply reviewed collection setup |
select(collectionId), clearSelection(), forget(collectionId) | Change or forget the selection |
destroy() | End the session |
describe()describechanges(input?)changeswatch(options?)changesread({ path })readquery(input?)queryqueryPages(input?, options?)queryqueryAll(input?, options?)querycreate(input)createupdate(input)updatepatch and optional revisionpreflightRename(input)renamerename(input)renamerenameWithProgress(input, options)renamepreflightDelete(input)deletedelete(input)deletedeleteWithProgress(input, options)deletevalidate(input?)validatedescribe()collection.readchanges(input?)collection.readwatch(options?)collection.readclose()read({ path })collection.readfile_not_found when missingquery(input?)collection.readqueryPages(input?, options?)collection.readqueryAll(input?, options?)collection.readcreate(input)records.createupdate(input)records.editpatch, optional body, and ifRevision; concurrent_modification when stalepreflightRename(input)records.editrename(input)records.editrenameWithProgress(input, options)records.editpreflightDelete(input)records.deletedelete(input)records.deletedeleteWithProgress(input, options)records.deletevalidate(input?)collection.readupdateType(). Updates require the source revision.
+
+ connection.records.open(path, options?) returns a lease on
+ the one shared MdbaseRecordSession for that record;
+ {" "}connection.records.follow(watch) keeps open sessions
+ current. Sessions provide setBody(),
+ {" "}patchFrontmatter(), save(),
+ {" "}flush(), refresh(), resolve(),
+ {" "}discard(), subscribe() and
+ {" "}getSnapshot(). See Editing
+ records.
+
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 |
authorizationCapabilities(required) | Compare required and granted operations (legacy v1 grants) |
requestCapabilities(capabilities, options?) | Request more declared capabilities 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 |
pendingMutations(), pendingMutation(requestId) | Durable handles for writes whose outcome is unknown, including after a reload |
pending.recover(options?) | Resend the exact original request; never a new write |
files | Upload, list, download, move, and delete collection files |
- Construct with any MdbaseCollectionTransport. It exposes the
+ Import from @mdbase-dev/connect/advanced and 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.
+ Expected failures are ConnectOutcome data:
+ {" "}{`{ ok: false, problem }`} with a stable
+ {" "}code, a category, a suggested
+ {" "}recovery, and code-specific details.
+
| Export | Purpose | ||||
|---|---|---|---|---|---|
unwrapOperation() | Return a valid result or throw validation diagnostics | ||||
MdbaseConnectError | Transport, authorization, routing, and request errors with recovery metadata | ||||
MdbaseOperationValidationError | Invalid canonical operation envelope | ||||
ConnectOutcome | The result type of every asynchronous operation | ||||
externalStore() | Adapt a session to useSyncExternalStore | ||||
MdbaseConnectError | Carries a problem through custom transports and adapters | ||||
isRetryableConnectError() | Classify transient Connect failures | ||||
parseMdbasePushPayload() | Validate a browser push envelope | ||||
parseMdbaseNativeNotificationData() | Validate string-valued FCM/APNs data |
| Feature | -Typical operations | +Capability | +Allows |
|---|---|---|---|
| Browse records | -describe, read, query |
- ||
| Live refresh | -changes |
- ||
| Edit records | -create, update |
- ||
| Move or remove records | -rename, delete |
- ||
| Use saved views | -list_views, execute_view |
- ||
| Administer saved view source | -read_view_source, create_view_source, update_view_source, delete_view_source |
- ||
| Administer collection types | -read_type, create_type, update_type |
- ||
| Authority timers | -list_timers, put_timer, cancel_timer, reconcile_timers |
- ||
collection.read | Describe the collection, read, query and watch records, use saved views, read types, validate | ||
records.create | Create records | ||
records.edit | Update and rename records | ||
records.delete | Delete records | ||
views.manage | Create, update and delete saved view sources | ||
definitions.manage | Create and update types, assess and apply type packs | ||
background.schedule | Authority timers | ||
offline.replica | Offline sync |
- Begin with the operations used by the current feature. Inspect the current - gap when a user opens an editing or administration feature. + Begin with the required capabilities. When a user opens a feature that + needs an optional one, ensure it then.
- requestOperations() is a no-op when the current grant is
- already sufficient. Otherwise it asks for the least-privilege union of the
- existing operations and the new requirements.
+ ensureCapabilities() returns unchanged when the
+ current grant already covers the request. Otherwise it asks for the
+ existing grant plus the new capabilities, and refuses capabilities the
+ manifest does not declare.
- The route is direct, relay, or
- {" "}hosted. Display it as status information. The SDK selects
- the route. The browser location subscription also reports back and forward
- selection changes. A null connection means the bookmarked
- collection has no usable authorization.
+ The session snapshot names its state: unselected,
+ {" "}authorization_required, checking_setup,
+ {" "}setup_review_required, ready,
+ {" "}unavailable, blocked, and the start-up
+ states. The route is direct, relay, or
+ {" "}hosted; display it as status information, as the SDK
+ selects it. Browser back and forward selection changes also notify
+ subscribers.
- MdbaseConnectError includes a machine-readable code, current
- grant information where relevant, and a recovery action:
- retry, reauthorize, refresh,
- resolve_outcome, fix_request, or{" "}
- none.
+ A failed outcome's problem has a machine-readable
+ {" "}code, a category, and a suggested
+ {" "}recovery, such as retry,
+ {" "}reauthorize, refresh,
+ {" "}resolve_outcome, resolve_conflict,
+ {" "}fix_request, or contact_support.
- Save this file at
- {" "}
+ It writes
- The contract requirement limits compatible collections. The type pack makes
- a collection safely provisionable during approval and does not give the
- application general type-management access.
+ connection.forget() clears only that collection's local
- authorization state. manager.forgetAll() clears the saved set.
+ authorization state. mdbase.forgetAll() clears the saved set.
Neither replaces user-controlled revocation at the
collection authority. Provide a clear path to the Connect controller when a
user needs to review, narrow, pause, or revoke a grant.
diff --git a/src/pages/sdk/connect-quickstart/index.astro b/src/pages/sdk/connect-quickstart/index.astro
index c4a20df..68074b5 100644
--- a/src/pages/sdk/connect-quickstart/index.astro
+++ b/src/pages/sdk/connect-quickstart/index.astro
@@ -11,29 +11,41 @@ const manifest = `{
"http://localhost:5173/auth/mdbase/callback"
],
"requirements": {
+ "access": "full_collection",
"contracts": [
- { "id": "workout.record", "version": "1.0.0" }
- ]
+ {
+ "id": "workout.record",
+ "version": "1.0.0",
+ "digest": "sha256:1b55e89c59ddeb7d6676af6fdc2792aa07cc78b89ea09f8f95001fad8455a180"
+ }
+ ],
+ "capabilities": {
+ "contract_version": 2,
+ "required": [
+ "collection.read",
+ "records.edit"
+ ]
+ }
},
"provisions": {
"type_packs": [
{
- "provides": [
- { "id": "workout.record", "version": "1.0.0" }
- ],
"manifest": {
"kind": "mdbase.type-pack",
"id": "example.workouts",
"version": "1.0.0",
+ "name": "Workouts",
"resources": [
{
"kind": "contract",
+ "mode": "managed",
"source": "contracts/workout.record.md",
"target": "_contracts/workout.record.md",
- "digest": "sha256:e0c2f77dd7158ca7e6b52b13da8c306f0a7e1b97582a1024f00ec0cf7fe5f259"
+ "digest": "sha256:0446184b7f36dd77e244cbe3c4ac97871cf9b78e7ff46a1e3686f542cecb32c2"
},
{
"kind": "type",
+ "mode": "seed",
"source": "types/workout.md",
"target": "_types/workout.md",
"digest": "sha256:ff35309cd4598182d2021f698ee85cad4d320d965cd5f7c1bd608ee2eb16505b"
@@ -43,12 +55,19 @@ const manifest = `{
"resources": [
{
"source": "contracts/workout.record.md",
- "document": "---\\nkind: mdbase.contract\\ncontract_type: record\\nid: workout.record\\nversion: 1.0.0\\nrecord_schema:\\n dialect: json-schema-2020-12\\n value:\\n $schema: https://json-schema.org/draft/2020-12/schema\\n type: object\\n additionalProperties: false\\n properties:\\n title: { type: string }\\n completed: { type: boolean, default: false }\\n required: [title]\\n---\\n"
+ "document": "---\\nkind: mdbase.contract\\ncontract_type: record\\nid: workout.record\\nversion: 1.0.0\\nrecord_schema:\\n dialect: json-schema-2020-12\\n value:\\n type: object\\n additionalProperties: false\\n properties:\\n title: { type: string }\\n completed: { type: boolean, default: false }\\n required: [title]\\n---\\n"
},
{
"source": "types/workout.md",
"document": "---\\nkind: mdbase.type\\nname: workout\\nversion: 1\\nschema:\\n dialect: json-schema-2020-12\\n value:\\n type: object\\n additionalProperties: true\\n properties:\\n title: { type: string }\\n completed: { type: boolean }\\n required: [title]\\nimplements:\\n - contract: workout.record\\n version: 1.0.0\\n fields:\\n title: title\\n completed: completed\\n---\\n"
}
+ ],
+ "provides": [
+ {
+ "id": "workout.record",
+ "version": "1.0.0",
+ "digest": "sha256:1b55e89c59ddeb7d6676af6fdc2792aa07cc78b89ea09f8f95001fad8455a180"
+ }
]
}
]
@@ -75,7 +94,7 @@ const validate = `mdbase-connect-dev validate-manifest \\
--allow-local`;
const client = `import {
- MdbaseBrowserLocation,
+ MdbaseBrowserSelection,
MdbaseConnect,
type JsonObject
} from "@mdbase-dev/connect";
@@ -85,97 +104,152 @@ export interface Workout extends JsonObject {
completed?: boolean;
}
-const loopback = new Set([
- "localhost",
- "127.0.0.1",
- "::1"
-]).has(location.hostname);
+const loopback = new Set(["localhost", "127.0.0.1", "::1"]).has(location.hostname);
export const mdbase = new MdbaseConnect1. Add a bundled application manifest
public/.well-known/mdbase-app.json. These loopback URLs are
- accepted by the local Connect stack. Pass --allow-local to the
- validator when checking this development manifest.
+ Generate the manifest from readable contract and type documents.
+ {" "}defineTypePack() computes every digest, so nothing is
+ copied by hand. Run it with Node after adding the packages in step 2.
+ public/.well-known/mdbase-app.json. These loopback
+ URLs are accepted by the local Connect stack; pass
+ {" "}--allow-local to the validator when checking this
+ development manifest.
requirements.capabilities declares what the application may
+ do: read the collection and edit records. The contract requirement limits
+ compatible collections. The type pack makes a collection safely
+ provisionable during approval and does not give the application general
+ type-management access.
2. Add the SDK and validator
@@ -263,37 +345,43 @@ if (first) {
- The manager owns saved authorizations. The location helper owns the
- bookmarkable collection ID, browser history changes, and authorization
- return cleanup.
+ MdbaseConnect owns saved authorizations. The application
+ session owns the selected collection (kept in the URL by
+ {" "}MdbaseBrowserSelection), authorization, and one snapshot
+ your interface subscribes to.
Connect presents ready and provisionable collections, then asks the user - to approve the listed operations. Collection records remain private until - approval succeeds. + to approve the capabilities the manifest declares. Collection records + remain private until approval succeeds.
-
- Call this once at the manifest's callback path. PKCE is mandatory. A
- successful callback stores the grant-bound authorization and returns a
- collection-bound connection.
+ Start the session once per page. At the manifest's callback path, complete
+ the authorization with the exact callback URL; PKCE is mandatory. Success
+ stores the grant-bound authorization and the snapshot becomes
+ {" "}ready, with a collection-bound connection. Every call
+ returns a ConnectOutcome: expected failures are data you
+ render, not exceptions.
- Query results carry an opaque revision. Passing it as
- {" "}if_revision prevents one application from silently
- overwriting a newer change.
+ A record read carries an opaque revision. Passing it as
+ {" "}ifRevision prevents one application from silently
+ overwriting a newer change: the update fails with
+ {" "}concurrent_modification instead. For a record people
+ type into, use a record session, which handles
+ revisions, autosave and conflicts for you.
Contract-scoped queries expose normalized mapped fields only. They union @@ -320,15 +408,15 @@ if (first) {
/auth/mdbase/callback.ready for the approved collection.completed: true.
-
+ An application that lets people type into a record should not call{" "}
+
+
+
+
+ A change made elsewhere is a conflict only when it touched something edited
+ locally: the body, or a frontmatter key the user changed. Otherwise the
+ session builds on the newer record without asking. If the other change
+ produced exactly the local text, the record is simply saved.
+
+
+ Applications that reach records through their own repository or a test
+ double construct the session with an adapter from{" "}
+
- Create one
- Record operations return
- Record-facing operations return{" "}
-
-
-
+ For a record people are typing into, use a{" "}
+ record session instead of issuing updates
+ yourself.
+
- MdbaseBrowserLocation writes
+ MdbaseBrowserSelection writes
{" "}?collection=<id> and follows browser back and forward
navigation. Collection IDs are opaque locators and can appear in browser
history and logs. They are not credentials.
diff --git a/src/pages/sdk/editing/index.astro b/src/pages/sdk/editing/index.astro
new file mode 100644
index 0000000..32f1c4c
--- /dev/null
+++ b/src/pages/sdk/editing/index.astro
@@ -0,0 +1,146 @@
+---
+import DocsLayout from "../../../components/DocsLayout.astro";
+import CodeBlock from "../../../components/CodeBlock.astro";
+
+const open = `const opened = await connection.records.open("Notes/today.md", {
+ autosave: { idleMs: 1_000 },
+ timeoutMs: 8_000
+});
+if (!opened.ok) return renderProblem(opened.problem);
+const { session, release } = opened.value;
+
+const unsubscribe = session.subscribe(() => render(session.getSnapshot()));
+editor.onChange((text) => session.setBody(text));
+properties.onChange((patch) => session.patchFrontmatter(patch));`;
+
+const follow = `const watch = await connection.watch({}, { timeoutMs: 20_000 });
+if (watch.ok) {
+ const stopFollowing = connection.records.follow(watch.value);
+ // On sign-out: stopFollowing(); watch.value.close();
+}`;
+
+const leave = `const flushed = await session.flush({ timeoutMs: 8_000 });
+if (!flushed.ok) {
+ if (flushed.problem.code === "concurrent_modification") {
+ showConflict(session.getSnapshot()); // local body and snapshot.remote
+ } else {
+ renderProblem(flushed.problem);
+ }
+}
+unsubscribe();
+release();`;
+
+const resolve = `session.resolve({ keep: "mine" }); // write local changes over the newer record
+session.resolve({ keep: "theirs" }); // take the newer record
+session.resolve({ body: merged }); // save text the user merged`;
+
+const react = `const store = externalStore(session);
+
+function useRecord() {
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
+}`;
+
+const adapter = `import { MdbaseRecordSession } from "@mdbase-dev/connect";
+import type { MdbaseRecordSessionAdapter } from "@mdbase-dev/connect/advanced";
+
+const adapter: MdbaseRecordSessionAdapterupdate() on every change. Open the record as a session
+ instead. The session saves after a pause in typing, never runs two writes
+ for the same record, and tells your interface what state the record is in.
+ Open a record
+ open() reads the record and returns a lease: the session and a{" "}
+ release() function for this view. Every view that opens the
+ same path shares one session, so an application never has two competing
+ writers for a record. Each save sends only the body and the frontmatter
+ keys that changed, checked against the revision they were based on.
+ Stay current while it is open
+ follow() routes collection changes to open sessions. A record
+ changed elsewhere is re-read, a renamed record keeps its session at the new
+ path, and a deleted record keeps its local text. After a change gap every
+ open record is re-read. The session recognizes its own saves, including
+ when the saved text comes back normalized before the save has finished,
+ so they are never mistaken for someone else's edit.
+ States
+
+
+ saved: the text is the saved record.unsaved: local changes wait for autosave or flush().saving: a write is in flight. Typing continues; newer text is saved next.conflict: the record changed elsewhere in a part edited locally.recovery: a save's response was lost. The same save is recovered exactly; nothing new is written until it is. This includes a save interrupted by a reload: open() resumes it.error: the last save failed. Local text is kept, and nothing retries in the background.deleted: the record no longer exists. Local text is kept.snapshot.problem holds the typed problem behind{" "}
+ error and recovery.
+ Resolve conflicts
+ Leave safely
+ flush() saves until nothing is left, or returns why it cannot.
+ Releasing the last view never cancels a save in progress; the session is
+ dropped once it has nothing left to save.
+ Use it from React
+ Records behind your own storage
+ @mdbase-dev/connect/advanced. Adapters report failures as{" "}
+ ConnectOutcome values. A file_not_found problem
+ from read marks the record deleted, and recover{" "}
+ must continue the original write through its pending mutation, never send
+ a new one.
+ @mdbase-dev/connect is the browser and native-shell SDK for
applications that operate on one user-approved local or hosted mdbase
- collection. The application asks for exact operations. Connect selects the
- route and the collection authority checks the current grant.
+ collection. The application declares the capabilities it needs in its
+ manifest. Connect selects the route and the collection authority checks
+ the current grant.
Starting points
@@ -97,12 +98,17 @@ export async function listOpenTasks(client: MdbaseCollectionClientBrowser APIs or adapters supplied by a native shell
-
- MdbaseBrowserLocationBookmarkable collection selection, authorization return URLs, and browser navigation
- A stable
+ MdbaseConnect manager and browser history APIs
+ MdbaseApplicationSessionOne application's collection selection, authorization, setup checks, and reactive snapshot
+ An
MdbaseConnect manager and a selection adapter such as MdbaseBrowserSelection
-
+
+ MdbaseCollectionClient
+ connection.recordsRecords people type into: autosave, conflicts, exact recovery, live updates
+ An
+ MdbaseConnection
+
@@ -121,11 +127,10 @@ export async function listOpenTasks(client: MdbaseCollectionClientMdbaseCollectionClient (/advanced)Domain and feature logic that should be independent of OAuth and hosting
A small
MdbaseCollectionTransportApplication structure
MdbaseConnect manager at the application boundary.
- Pair it with one MdbaseBrowserLocation at the browser
- application boundary. Resolve its active connection, then pass that
- {" "}MdbaseConnection into feature code. The location helper owns
- bookmark selection and OAuth return cleanup; the manager owns saved
+ Create one MdbaseConnect manager and one application session
+ at the application boundary. Read the session's active connection, then
+ pass that MdbaseConnection into feature code. The session owns
+ collection selection and authorization; the manager owns saved
authorizations. A bound connection never changes collections underneath a
repository, and feature code written against
{" "}MdbaseCollectionClient can also run against the developer
@@ -139,12 +144,13 @@ export async function listOpenTasks(client: MdbaseCollectionClient{`{ valid, result, diagnostics }`}.
- Use unwrapOperation() when exceptions suit the calling code,
- or inspect the envelope when the interface should present validation
- diagnostics inline.
+ Every operation returns a ConnectOutcome:
+ {" "}{`{ ok: true, value, diagnostics }`} or
+ {" "}{`{ ok: false, problem }`}. Expected failures are data
+ with a stable code and a suggested recovery; exceptions mean a
+ programming error.
Operation envelopes
+ Typed outcomes
{`MdbaseOperationEnvelope. A successful envelope
- contains valid: true, the typed result, and any non-fatal
- diagnostics. Validation failures return diagnostics in the same envelope.
- Transport failures use exceptions.
+ Every operation returns a ConnectOutcome. Check{" "}
+ ok: a success has the typed value and any
+ non-fatal diagnostics; a failure has a problem{" "}
+ with a stable code, a category, a suggested{" "}
+ recovery, and, for mutations, whether the write was sent,
+ rejected or has an unknown outcome. Expected failures are data, not
+ exceptions; exceptions mean a programming error.
unwrapOperation(envelope) returns the result or throws{" "}
- MdbaseOperationValidationError. Use it when the calling layer
- uses exceptions. Keep the raw envelope when diagnostics are part of the
- interface.
+ Record conditions have one code whichever authority holds the collection:
+ a stale revision is concurrent_modification, a missing record
+ is file_not_found, and invalid input is{" "}
+ operation_invalid with the mdbase diagnostics in its details.
Read one path or query a collection
@@ -114,8 +121,9 @@ await connection.renameWithProgress({
Page large result sets against one snapshot
queryPages() preserves the snapshot token returned by the
- first page and rejects a changed token. queryAll() provides the
+ queryPages() yields one outcome per page. It preserves the
+ snapshot token returned by the first page and reports a changed token as
+ {" "}query_snapshot_changed. queryAll() provides the
same behavior when holding the complete result set in memory is acceptable.
patch is the canonical v0.3 partial-frontmatter update. A
- mismatched if_revision produces{" "}
+ mismatched ifRevision produces{" "}
concurrent_modification. Refresh the record and ask the user or
domain logic to resolve the conflict before submitting another write.
Resume changes by cursor
watch() uses the collection authority's resumable change
- cursor. The local change feed remains at the collection authority. The
- iterator reconnects transient routes by default and reports{" "}
- reset_required when the consumer must refresh a complete view.
+ watch() starts within a bounded budget and returns a
+ subscription that lasts until close() or its lifetime signal.
+ It resumes from the collection authority's change cursor, reconnects
+ transient routes by default, and reports a reset_required{" "}
+ status when the consumer must refresh a complete view. To keep open
+ records current, pass the subscription to{" "}
+ connection.records.follow().
Show authoritative impact before destructive work
@@ -145,13 +162,14 @@ await connection.renameWithProgress({
renameWithProgress() or deleteWithProgress() so
the confirmation shown to the user matches the operation that will run.
- If the caller stops waiting after dispatch, inspect{" "}
- pendingMutation() and recover the exact connector receipt
- with resumePendingMutation(). Wait for that outcome before
- submitting a different mutation.
-
+ The SDK stores each mutation's exact encrypted request before sending it.
+ If the response is lost, the write fails with{" "}
+ operation_outcome_unknown and a durable handle appears in{" "}
+ pendingMutations(), including after a reload.{" "}
+ recover() resends the original request identity; never repeat
+ the write as a new mutation. Record sessions do this for you.
+
createSandbox() returns the same
{" "}MdbaseCollectionClient boundary used by a connected
collection. The example reads one seed record, creates a second record,
- updates it with its revision token, and queries both task records.
+ updates it with its revision token, shows that a stale revision is
+ refused, and queries both task records. Every operation returns a{" "}
+ ConnectOutcome: check ok, then use{" "}
+ value or problem. Expected failures are data,
+ not exceptions.
- A stale revision fails with a
- {" "}concurrent_modification diagnostic. The sandbox also supports
+ A stale revision fails with the
+ {" "}concurrent_modification problem, the same code a real
+ collection returns. The sandbox also supports
typed CRUD, pagination, read defaults, and change cursors. CEL expressions,
authorization, routing, and filesystem behavior belong in real-stack
integration tests.
diff --git a/src/pages/sdk/testing/index.astro b/src/pages/sdk/testing/index.astro
index dbd8c99..4ec0372 100644
--- a/src/pages/sdk/testing/index.astro
+++ b/src/pages/sdk/testing/index.astro
@@ -4,6 +4,7 @@ import CodeBlock from "../../../components/CodeBlock.astro";
const sandbox = `import { createSandbox } from "@mdbase-dev/connect-dev";
import type { JsonObject } from "@mdbase-dev/connect";
+import type { MdbaseCollectionClient } from "@mdbase-dev/connect/advanced";
interface Task extends JsonObject {
type: "task";
@@ -11,21 +12,41 @@ interface Task extends JsonObject {
status: "open" | "done";
}
-const { client, transport } = createSandbox
-
Typed CRUD and operation envelopes
+ Typed CRUD and outcomes
CEL expression semantics
@@ -88,10 +110,24 @@ pnpm e2e`;
- The sandbox rejects where and order_by. Run CEL
+ The sandbox rejects where and orderBy with sandbox_unsupported. Run CEL
expression and ordering tests against a conforming collection authority.
+ createRecordTestAuthority() from
+ {" "}@mdbase-dev/connect-testing is an in-memory authority
+ with revision checks and a change watch; its records is the
+ real connection.records implementation. Controls reproduce
+ what other clients and the network do: editElsewhere(),
+ {" "}renameElsewhere(), deleteElsewhere(),
+ {" "}loseNextResponse(), failNextWrite() and
+ {" "}resetWatch(), with writes recording what
+ reached the authority.
+
Run integration tests against the local Connect stack for:
- Preserve the revision returned by reads and queries, then pass{" "}
- if_revision to update, rename, and delete operations.
+ Preserve the revision returned by a read or write, then pass{" "}
+ ifRevision to update, rename, and delete operations.
Resolve conflicts explicitly.