Skip to content

Connector API Reference

This is the reference for connector contract 0.4. The single source of truth is src/connector/def.ts in the plugin repository; the SDK’s index.d.ts is generated from it, so the two cannot drift.

Companion npm package: @sync-vault/connector-sdk (types and local debugging tools only, no runtime code).

Terminal window
npm install --save-dev @sync-vault/connector-sdk
  • Current contract version: 0.4.
  • Compatibility checks only the first segment of apiVersion: the host is 0.4, so 0.4.x and 0.2.9 are both compatible; 1.x is not.
  • 0.3 added the parts-related fields and 0.4 added the audio-source type. Both only added optional capabilities, so older connectors need no changes.
<vault>/.obsidian/plugins/sync-vault-ce/connectors/<connector id>/
├── manifest.json Required
├── main.js Required
└── settings.json Optional; read/written by ctx.getSettings / saveSettings
  • The plugin scans once on startup. Afterwards, run Reload user connectors from the command palette.
  • Scanning is in ascending directory-name order, which is also registration and match order.
  • One failing connector does not affect other connectors or plugin startup. The failure reason appears in the Connectors widget and in the log.
  • Reloading calls dispose() on the old instance before creating the new one. Disabling the plugin disposes every connector.
  • Disabling uses a .disabled marker inside the directory: files and settings are kept, but the connector is not evaluated or matched. Uninstalling deletes the whole directory.
FieldRequiredDescription
idYesUnique identifier; must match the directory name; [a-z0-9-_], starting with a letter or digit
nameYesDisplay name
versionYesThe connector’s own version
apiVersionYesTarget contract version, e.g. 0.4
typeYesvideo-source, audio-source, or agent-session
descriptionNoOne-line description
authorNoAuthor
homepageNoRepository or homepage URL

A missing field, an invalid id, an id that does not match the directory, an unsupported type, or a mismatched apiVersion first segment all cause an explicit load failure.

Must be a single CommonJS file:

module.exports = {
create(ctx) {
return {
// Implement the methods required by your type
};
},
};
  • ESM import / export is not supported; the host evaluates the file as CommonJS.
  • There is no require at runtime: node_modules and Node built-ins are unavailable. Get every capability from ctx.
  • Top-level code runs once at load; create(ctx) may be async.
  • With TypeScript or multiple source files, bundle dependencies into a single main.js (the SDK’s templates/ts has a ready-made setup).
MemberDescription
idThis connector’s id
dirThis connector’s directory inside the vault
platform{ isDesktop, isMobile } for per-platform behavior
request(options)Network requests through the host channel, not subject to browser CORS
logdebug / info / warn / error, written to the Sync Vault log
getSettings<T>()Reads settings.json; returns null when the file does not exist
saveSettings(obj)Writes settings.json (JSON with 2-space indentation)
desktopDesktop-only file channel outside the vault; undefined on mobile
const resp = await ctx.request({
url: 'https://api.example.com/x',
method: 'GET', // Optional, defaults to GET
headers: { 'Referer': 'https://example.com' }, // Optional
body: JSON.stringify(payload), // Optional, string | ArrayBuffer
});
resp.status; // number
resp.headers; // Record<string, string>, keys lowercased
resp.text; // string
resp.json; // any, parsed on access
resp.arrayBuffer; // ArrayBuffer
  • Non-2xx responses do not throw: check status yourself. Only network-layer failures (offline, DNS) throw.
  • Response bodies are read lazily. Do not assume a large body can be read twice.

Suitable for tokens and cookies. It is an ordinary file in the vault, stored in plain text, and travels with sync and sharing. Do not hard-code long-lived secrets in main.js.

interface VideoSourceConnector {
match(url: string): boolean;
resolve(url: string, onProgress?: (message: string) => void): Promise<MediaStreamInfo>;
dispose?(): void | Promise<void>;
}
  • match(url): whether this connector handles the address. The host calls it synchronously, so it must be cheap — no network requests.
  • When multiple connectors match, the first in ascending directory-name order wins, and that connector owns the address entirely.
  • resolve(url, onProgress): resolves a playable stream. onProgress messages are shown in the player’s loading state.
  • A failed resolve must throw an explicit error. The host will not fall back to built-in parsing, try another connector, or silently treat the address as a direct link.
  • When the URL expires, the host calls resolve again with the same URL, so the implementation must be repeatable.
FieldRequiredDescription
urlYesThe address to play
urlTypeYesdirect for a single address; m3u8-list for an HLS playlist
mediaTypeYesraw for a direct link; hls for hls.js / native HLS
mediaInfoYesAvailable qualities, at least one item
headersNoHeaders to send while playing
proxyNotrue routes direct links through the host’s local proxy; requires headers to take effect
coverUrlNoCover image
cursorNoLast playback position in seconds
partsNoPart list
currentPartIndexNoIndex of the part this result represents; defaults to 0
cleanupNoCalled when this stream is replaced or the player is destroyed

Each mediaInfo item:

FieldRequiredDescription
urlYesAddress for this quality
resolutionYesDisplay name such as 1080P or Auto
width / heightYesPixel dimensions for the player’s initial aspect ratio; use 0 when unknown
OthersNoduration / codec / frameRate / audioCodec / sampleRate / fileSize

Conventions:

  • streamInfo.url should equal one mediaInfo[].url; that item’s resolution becomes the current quality.
  • resolution: '原画' is special: selecting this quality takes the direct-link path (hls.js is torn down and the URL is set on <video> directly). Do not use 原画 for HLS streams, or that quality will not play through HLS.
return {
url: current.playUrl,
urlType: 'm3u8-list',
mediaType: 'hls',
mediaInfo: [{ url: current.playUrl, width: 0, height: 0, resolution: 'Auto' }],
parts: [
{ name: 'P1 Intro', url: 'https://www.bilibili.com/video/BV1xx411c7mD?p=1' },
{ name: 'P2 Main', url: 'https://www.bilibili.com/video/BV1xx411c7mD?p=2' },
],
currentPartIndex: 1,
};
  • Parts are shown only when there are at least 2 items; a single part can be omitted.
  • The host re-invokes resolve with a part’s url when switching, so every URL must be handled by match / resolve.
  • currentPartIndex identifies the part this result represents. If an invalid ?p= fell back to a different part, return the index actually played.
  • Parts are independent entries in the host: each keeps its own progress and annotation anchors, and the next part auto-continues when one ends.

Playback URLs from platforms usually expire (signed CDN links and similar). The host compensates:

  • On 401 / 403 / 404 / 410 during playback, it calls resolve again with the same URL, then resumes from the previous position.
  • Each player reloads at most 2 times; the quota is restored if playback runs for 1 minute without expiring again.
  • When a MediaStreamInfo is replaced (expiry reload, video switch) or the player is destroyed, the host calls its cleanup(). Put one-shot resources (timers, local servers, temporary subscriptions) in cleanup; resources that must span multiple streams belong in the instance’s dispose.

Audio sources currently have no expiry reloads — see the next section.

interface AudioSourceConnector {
match(url: string): boolean;
resolve(url: string, onProgress?: (message: string) => void): Promise<MediaStreamInfo>;
dispose?(): void | Promise<void>;
}

The method shape, match order, and error semantics are identical to video sources; the host uses its audio player for the result. Differences:

  • Audio has no resolution. Set width: 0 and height: 0 in every mediaInfo item and use 原画 or a display name for resolution.
  • If an address matches both a video source and an audio source, it is treated as video: video sources are asked first, and audio sources only when none match.
  • No expiry reloads: if the URL stops working during playback, the host will not call resolve again. Return an address that remains valid long enough.
  • parts play in order. The part list appears in the player sidebar (right-click an audio block and choose Open sidebar); the embedded player has no part selector.
  • cleanup follows the same timing as video sources.

Exports an agent’s local sessions into the managed repository so another device can restore them and continue. The host owns the managed repository, version cursors, and cross-device distribution; the connector only knows that agent’s storage layout and restore procedure.

interface AgentSessionConnector {
probe(): Promise<AgentSessionProbeResult>;
discover(): Promise<AgentSessionRef[]>;
export(ref: AgentSessionRef): Promise<AgentSessionBundle>;
stage(bundle: AgentSessionBundle, env: DeviceEnv): Promise<ResumePlan>;
watch?(ref: AgentSessionRef, onChange: () => void): () => void;
}
  • All four of probe / discover / export / stage are required; a missing one rejects the connector.
  • stage(bundle, env) writes the bundle back to the correct local location and returns a ResumePlan (resume command, suggested cwd, notes). It never executes commands.
  • Bundle paths are relative to the session directory; entries containing .., absolute paths, or backslashes are rejected by the host.
  • watch is an optional enhancement; without it, the host detects changes by comparing the nativeMtime / nativeSize cursors.
  • Desktop only: files outside the vault must go through ctx.desktop, which is undefined on mobile. Mobile can only view sessions already added to sync.

See examples/qoder in the SDK for a complete implementation.

For addresses behind anti-hotlink checks (requiring Referer and similar), return proxy: true together with headers:

  • Desktop: direct links go through a local 127.0.0.1 proxy that adds the headers and CORS response headers.
  • Mobile: there is no local proxy. proxy: true degrades to a direct connection, headers for direct links are not applied, and addresses that require them will fail with 403. Detect this in resolve and throw an explicit error.
  • HLS: when headers are set, the host prefers hls.js and loads playlists and segments through its own request channel, so headers are applied on both desktop and mobile. If hls.js is unavailable, native HLS is used and headers cannot be applied.

CORS requirements:

  • Direct video is loaded through <video crossorigin="anonymous">, so the origin must return Access-Control-Allow-Origin; otherwise playback fails with MEDIA_ELEMENT_ERROR: Format error — which looks like an encoding problem but is a CORS rejection. On desktop, proxy: true lets the local proxy add the headers; on mobile there is no proxy.
  • Direct audio is loaded through <audio> without crossorigin, so the origin does not need CORS headers.
  • HLS playlists and segments fetched through the host request channel are not subject to browser CORS.

To test an origin, run curl -H 'Origin: app://obsidian.md' -I <url> and check for access-control-allow-origin.

  • Mobile compatibility: connectors are loaded and executed on iOS / Android too. Node built-ins (fs, path, http, …) and Electron-only APIs are unavailable; use Web standards such as crypto.subtle for randomness or digests.
  • File access: inside the vault, use only getSettings / saveSettings. Local files outside the vault are available only to agent-session connectors, and only through ctx.desktop on desktop.
  • No sandbox: connectors run with the plugin’s privileges and can make network requests and read/write their own settings. Install only trusted sources.
  • Do not block: keep match synchronous and cheap; put slow work in resolve.
Terminal window
# Video / audio: load → match → resolve
npx sync-vault-connector-mock ./my-connector "https://example.com/video/1"
# agent-session: load → probe → discover
npx sync-vault-connector-mock ./my-connector

The mock validates and evaluates exactly like the host, catching manifest field errors, ESM syntax, missing require, and similar issues early.

After installing into the vault:

  1. Run Reload user connectors and check the “N loaded, M failed” notice.
  2. When playback fails, search the log for [connector.<id>]; errors thrown by resolve are recorded there.