### SDK s() helper example Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Complete example of using the `s()` helper to define a parent group and its child toggle, with imports and function signature. ```typescript import type { Context, CallableOrObjectTree } from '@hesprs/sync-engine-sdk'; import type { SettingGroupItem } from 'obsidian'; import { s } from '@hesprs/sync-engine-sdk'; export default function mySettings( ctx: Context, settings: { enabled: boolean }, ): CallableOrObjectTree { return { 2000: s( (self) => ({ heading: ctx.translate('mySettings'), items: Object.values(self).map((node) => node(node) as SettingGroupItem), type: 'group', }), { 1000: s(() => ({ control: { key: 'enabled', type: 'toggle' }, name: ctx.translate('enabled'), })), }, ), }; } ``` -------------------------------- ### Start WebDAV server with rclone Source: https://github.com/hesprs/sync-engine/blob/main/scripts/benchmark/testing.md Starts a local WebDAV server on port 5005 serving the specified directory. Accepts any username and password. ```sh rclone serve webdav /home/hesprs/Desktop/DAV --addr :5005 ``` -------------------------------- ### Module sources setting example Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/distribution.md Example of the moduleSources setting that stores URLs from which the plugin reads module source JSON files. ```ts moduleSources: ['https://sync.consensia.cc/modules.json']; ``` -------------------------------- ### GET /meta/{key} Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Get metadata from a database. ```APIDOC ## [GET] /meta/{key} ### Description Get metadata from a database. ### Method GET ### Endpoint /meta/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The metadata key. ### Request Example ```ts const meta = db.getMeta('key'); ``` ### Response #### Success Response (200) - **value** (any) - The metadata value. #### Response Example ```ts { "value": "metadata value" } ``` ``` -------------------------------- ### Using getRecordStore to set and get records Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Shows how to obtain the current RecordStore and use its set and get methods. When no backend is set, getRecordStore() returns an Error. ```typescript const records = ctx.getRecordStore(); await records.set('note.md', { isDir: false, local: 'local-uid', remote: 'remote-uid', }); const record = await records.get('note.md'); ``` -------------------------------- ### pipe usage example Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/sync.md Shows how to call pipe with a remote filesystem as source and local filesystem as destination, copying the file at 'folder/note.md'. ```typescript await pipe({ from: remoteFs, to: localFs, key: 'folder/note.md', stat }); ``` -------------------------------- ### GET /stores/{storeName} Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Retrieve a store from a database. Stores expose get, set, delete, clear, keys, values, entries, and batch operations. ```APIDOC ## [GET] /stores/{storeName} ### Description Retrieve a store from a database. Stores expose get, set, delete, clear, keys, values, entries, and batch operations. ### Method GET ### Endpoint /stores/{storeName} ### Parameters #### Path Parameters - **storeName** (string) - Required - The name of the store to retrieve. ### Request Example ```ts const store = db.getStore('localContext20000'); ``` ### Response #### Success Response (200) - **store** (StoreAsync | StoreSync) - The requested store. #### Response Example ```ts { "store": "StoreAsync" } ``` ``` -------------------------------- ### Initialize project and install SDK with Bun Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Run these commands in a new project folder to initialize a Bun project and add the official Sync Engine SDK plus the tsdown bundler as dev dependencies. Use any package manager; this documentation uses Bun throughout. ```sh bun init -y bun add -D @hesprs/sync-engine-sdk tsdown ``` -------------------------------- ### Resulting My settings group tree Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Text representation of the setting tree produced by the SDK example. ```text 2000 My settings (group) └── 1000 Enabled (toggle) ``` -------------------------------- ### Module root property example Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/deep-dive/architecture.md Shows how a module publishes its capabilities through a root property, which SynthKernel merges into the shared context. ```typescript root = { executeSync: this.executeSync, }; ``` -------------------------------- ### startScheduledSync() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Starts interval sync. ```APIDOC ## startScheduledSync() ### Description Starts interval sync. ### Method Function ### Signature `startScheduledSync()` ``` -------------------------------- ### GET /stores Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md List all store names in a database. ```APIDOC ## [GET] /stores ### Description List all store names in a database. ### Method GET ### Endpoint /stores ### Parameters None ### Request Example ```ts const names = db.getStoreNames(); ``` ### Response #### Success Response (200) - **storeNames** (string[]) - Array of store names. #### Response Example ```ts { "storeNames": ["localContext20000", "remoteContext10000", "remoteContext20000"] } ``` ``` -------------------------------- ### modules.json module entry Source: https://github.com/hesprs/sync-engine/blob/main/CONTRIBUTING.md Example entry to add to modules.json at the repo root to register a new official module. ```json [ { "name": "Module Name", "id": "your-module", "icon": "puzzle", "description": "Description for your module", "version": "0.0.1", "main": "https://sync.consensia.cc/modules/module-name.js" } ] ``` -------------------------------- ### GET /databases Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Access the two database instances provided on the Context object: an async IndexedDB database and a synchronous in-memory database. ```APIDOC ## [GET] /databases ### Description Access the async IndexedDB database and synchronous in-memory database on the Context object. ### Method GET ### Endpoint /databases ### Parameters None ### Request Example ```ts const asyncDB = ctx.indexedDB; const syncDB = ctx.memoryDB; ``` ### Response #### Success Response (200) - **indexedDB** (DatabaseAsync) - Async IndexedDB database. - **memoryDB** (DatabaseSync) - Synchronous in-memory database. #### Response Example ```ts { "indexedDB": "DatabaseAsync", "memoryDB": "DatabaseSync" } ``` ``` -------------------------------- ### Subscribe and dispatch events with ctx.on and ctx.dispatch Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/events.md Shows how to subscribe and dispatch events using ctx.on and ctx.dispatch. The example subscribes to 'syncTerminated', dispatches a 'logGeneral' message, dispatches the payloadless 'syncCanceled', and calls the returned unsubscribe cleanup. ```ts import type { Events, On, Dispatch } from '@hesprs/sync-engine-sdk'; const on: On = ctx.on; const on: Dispatch = ctx.dispatch; const unsubscribe = on('syncTerminated', (reason) => { if (reason.result === 'failed') console.error(reason.error); }); dispatch('logGeneral', 'Example module started.'); dispatch('syncCanceled'); unsubscribe(); ``` -------------------------------- ### Create S3 bucket with AWS CLI Source: https://github.com/hesprs/sync-engine/blob/main/scripts/benchmark/testing.md Creates the S3 bucket 'obsidian-sync' on the local RustFS endpoint. Uses the access key and secret from the RustFS setup. ```sh export AWS_ACCESS_KEY_ID="syncengine2026" export AWS_SECRET_ACCESS_KEY="rustfs-test-secret" export AWS_DEFAULT_REGION="us-east-1" aws s3api create-bucket --bucket obsidian-sync --endpoint-url http://127.0.0.1:5005 ``` -------------------------------- ### GET /record-store Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Get the current or named RecordStore. Returns an Error if no backend is set. ```APIDOC ## [GET] /record-store ### Description Get the current or named RecordStore. Returns an Error if no backend is set. ### Method GET ### Endpoint /record-store ### Parameters #### Query Parameters - **name** (string) - Optional - The name of the record store to retrieve. ### Request Example ```ts const records = ctx.getRecordStore(); ``` ### Response #### Success Response (200) - **recordStore** (RecordStore) - The record store. #### Response Example ```ts { "recordStore": "StoreAsync" } ``` ``` -------------------------------- ### Load CSS in a module Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Example module that imports a CSS file inline and registers it with the context, with cleanup on dispose. ```TypeScript import type { Context } from '@hesprs/sync-engine-sdk'; import css from './styles.css?inline'; export default class MyModule { readonly cleanup: Array<() => void> = []; constructor(private readonly ctx: Context) {} start(): void { cleanup.push( this.ctx.registerCss(css), // ... other registrations ) } dispose(): void { this.cleanup.splice(0).forEach((fn) => fn()); } } ``` -------------------------------- ### Example of non-consecutive numeric keys Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Shows that numeric keys in a setting tree do not need to be consecutive; they only provide sibling order. ```typescript { 1000: /* first item */, 3000: /* second item */, // 2000 is not required } ``` -------------------------------- ### Install @tsdown/css package Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Adds the Tsdown CSS package as a dev dependency to enable CSS processing. ```sh bun add -D @tsdown/css ``` -------------------------------- ### Module source JSON schema example Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/distribution.md A JSON array describing a module entry with fields id, name, version, description, main, and integrity. The plugin validates all six required fields and rejects entries missing any of them. ```json [ { "id": "webdav", "name": "WebDAV", "version": "0.0.2", "description": "WebDAV backend support.", "main": "https://sync.consensia.cc/modules/webdav.js", "integrity": "abc123..." } ] ``` -------------------------------- ### MyFs class implementing RootFs Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/file-system.md Example class implementation of RootFs. The getUid method follows the convention '~~...' using '~' as delimiter. Backends can implement methods beyond RootFs for special capabilities and use digOriginal to access them from wrappers or optimizers. ```ts import type { Progress, RootFs, Stat, Request } from '@hesprs/sync-engine-sdk'; export type MyFsOptions = { endpoint: string; apiKey: string; }; export class MyFs implements RootFs { constructor( private readonly options: MyFsOptions, private readonly request: Request, ) {} getUid(): string { return `mybackend~${this.options.endpoint}~${this.options.apiKey}`; } // ... implement all methods, using this.request for network calls } ``` -------------------------------- ### Core settings Features group registration Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Example of a core settings registration that creates a 'Features' group with a 'Realtime sync' toggle child. ```typescript { 1000: s( (self) => ({ heading: 'Features', items: Object.values(self).map((node) => node(node)), type: 'group', }), { 1000: s(() => ({ name: 'Realtime sync', control: { key: 'realtime', type: 'toggle' } })), }, ), } ``` -------------------------------- ### getCheckConnection() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Gets the selected backend connection-check function. ```APIDOC ## getCheckConnection() ### Description Gets selected backend connection-check function. ### Method Function ### Signature `getCheckConnection()` ### Returns - Connection-check function. ``` -------------------------------- ### Minimal Sync Engine module (index.ts) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Minimal module skeleton showing the required default export class, Context injection, optional moduleSettings, start(), and dispose() lifecycle methods. ```TypeScript import type { Context } from '@hesprs/sync-engine-sdk'; export default class MyModule { constructor(private readonly ctx: Context) {} readonly moduleSettings = { // Declare persistent settings with default values }; start(): void { // Configure resources needed by the plugin // Register capabilities } dispose(): void { // Unregister capabilities and release resources } } ``` -------------------------------- ### S3 Batch Delete Optimizer Implementation Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/file-system.md An example optimizer that groups multiple delete operations into a single batch request for S3 file systems. ```ts import type { DeleteAtom, OptimizerInput, OptimizerOutput } from '@hesprs/sync-engine-sdk'; import { digOriginal } from '@hesprs/sync-engine-sdk'; import S3Fs from './s3/fs'; export default function s3BatchDeleteOptimizer({ atoms, fs, }: OptimizerInput): OptimizerOutput | undefined { const original = digOriginal(fs); if (!(original instanceof S3Fs)) return; const deleteAtoms = atoms.filter((a): a is DeleteAtom => a.type === 'delete'); if (deleteAtoms.length <= 1) return atoms; const otherAtoms = atoms.filter((a) => a.type !== 'delete'); const batchAtom = { execute: async () => { const keys = deleteAtoms.map((a) => a.key); try { const result = await original.batchDelete(keys); deleteAtoms.forEach((atom) => { const status = result[atom.key]; if (status) atom.reject(status); else atom.resolve(); }); } catch (error) { const reason = error instanceof Error ? error : new Error(String(error)); deleteAtoms.forEach((atom) => atom.reject(reason)); } }, type: 'custom' as const, }; return [...otherAtoms, batchAtom]; } ``` -------------------------------- ### syncEngineModule plugin configuration with magic bytes metadata Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Pass module metadata to the syncEngineModule plugin to prepend a magic bytes comment to each compiled entry file. The metadata object includes name, icon, description, source, version, and readme fields. The output file then starts with a comment block containing the same fields. ```TypeScript plugins: [ syncEngineModule({ name: 'My Module', icon: 'puzzle', description: 'An example module.', source: 'https://example.com/modules.json', version: '1.0.0', readme: 'https://example.com/my-module', }), ], ``` ```js /*! name: My Module icon: puzzle description: An example module. source: https://example.com/modules.json version: 1.0.0 readme: https://example.com/my-module */ ``` -------------------------------- ### GET /record-store/exists Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Test whether the current or named record store exists. ```APIDOC ## [GET] /record-store/exists ### Description Test whether the current or named record store exists. ### Method GET ### Endpoint /record-store/exists ### Parameters #### Query Parameters - **name** (string) - Optional - The name of the record store to check. ### Request Example ```ts const exists = ctx.recordStoreExists(); ``` ### Response #### Success Response (200) - **exists** (boolean) - Whether the record store exists. #### Response Example ```ts { "exists": true } ``` ``` -------------------------------- ### Register debugWrapper with registerRemoteFsWrapper Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/debug-and-testing.md Example of registering debugWrapper as a remote FS wrapper with high priority to log all filesystem calls during debugging. ```ts import { debugWrapper } from '@hesprs/sync-engine-sdk/dev'; ctx.registerRemoteFsWrapper({ priority: 9999, apply: (fs) => debugWrapper(fs, console.log), }); ``` -------------------------------- ### initializeSync() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Creates local FS, remote FS, and record store for sync. ```APIDOC ## initializeSync() ### Description Creates local FS, remote FS, and record store for sync. ### Method Function ### Signature `initializeSync()` ### Returns - Initialized sync components (local FS, remote FS, record store). ``` -------------------------------- ### Import testKit and create fs harness Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/debug-and-testing.md Import the test harness and create a stub filesystem and binary content for FS or request tests. ```ts import { testKit } from '@hesprs/sync-engine-sdk/dev'; const { fs, bytes } = testKit; const harness = fs(); const content = bytes('hello'); ``` -------------------------------- ### Typical Sync Engine module structure Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Shows the recommended file layout for a Sync Engine module, including optional i18n.ts and setting.ts files, the module entry, tests, and build configuration. ```txt your-module ├── src │ ├── i18n.ts (optional: translation objects) │ ├── index.ts (module entry) │ ├── setting.ts (optional: settings factory) │ └── ... ├── test (if you want tests) │ └── ... ├── package.json ├── tsconfig.json ├── tsdown.config.ts └── ... (linter, formatter, etc.) ``` -------------------------------- ### getConflictResolver() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Gets the selected ConflictResolver. ```APIDOC ## getConflictResolver() ### Description Gets selected `ConflictResolver`. ### Method Function ### Signature `getConflictResolver()` ### Returns - Selected `ConflictResolver`. ``` -------------------------------- ### createLocalFs() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Creates a wrapped local filesystem instance. ```APIDOC ## createLocalFs() ### Description Creates a wrapped local filesystem. ### Method Function ### Signature `createLocalFs()` ### Returns - Local filesystem wrapper (type not specified) ``` -------------------------------- ### showProgress() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Opens progress UI. ```APIDOC ## showProgress() ### Description Opens progress UI. ### Method Function ### Signature `showProgress()` ``` -------------------------------- ### getRequest() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Gets the composed remote request function. ```APIDOC ## getRequest() ### Description Gets composed remote request function. ### Method Function ### Signature `getRequest()` ### Returns - Composed remote request function. ``` -------------------------------- ### getVaultRequest() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Gets the composed local vault request function. ```APIDOC ## getVaultRequest() ### Description Gets composed local vault request function. ### Method Function ### Signature `getVaultRequest()` ### Returns - Composed local vault request function. ``` -------------------------------- ### Using prefixWrapper to create a scoped file system Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/file-system.md Shows how to use the prefixWrapper runtime export to create a scoped file system that prefixes all paths with a base directory. The write call delegates to the underlying remoteFs with the prefixed path. ```ts import { prefixWrapper } from '@hesprs/sync-engine-sdk'; const scopedFs = prefixWrapper(remoteFs, 'team/vault/'); await scopedFs.write('notes/today.md', value, stat); // Delegates to remoteFs.write('team/vault/notes/today.md', value, stat) ``` -------------------------------- ### Registering and removing settings Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Shows how to register the returned setting tree during module startup and remove it during disposal. ```typescript const removeSettings = ctx.registerSetting({ apply: mySettings(ctx, this.moduleSettings), priority: 1355, }); this.cleanup.push(removeSettings); ``` -------------------------------- ### TaskFactory Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/sync.md Creates task instances for various sync operations. Each task requires a `key` and task-specific options. ```APIDOC ## TaskFactory ### Description Creates task instances for various sync operations. Each task requires a `key` and task-specific options. ### Method TaskFactory ### Signature ```ts type TaskFactory = ( name: N, options: TaskOptionsMap[N], ) => InstanceType<(typeof taskMap)[N]>; ``` ### Parameters - **name** (TaskNames) - Required - The name of the task to create. Valid values: 'addRecord', 'removeRecord', 'createLocalDir', 'createRemoteDir', 'download', 'resolveConflict', 'removeLocal', 'removeRemote', 'upload', 'moveLocal', 'moveRemote'. - **options** (TaskOptionsMap[N]) - Required - Task-specific options. All tasks require `key`. Additional required options vary by task type. ### Returns InstanceType<(typeof taskMap)[N]> - A task instance of the specified type. ### Task Types | Type | Required options beyond `key` | Operation | | ----------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `AddRecord` | `local: Stat`, `remote: Stat` | Creates record for both sides. File records contain both UIDs; directory records contain `isDir`. | | `RemoveRecord` | None | Deletes sync record without changing either filesystem. | | `Download` | `remote: FileStat` | Copies remote file to local filesystem and records both UIDs. | | `Upload` | `local: FileStat` | Copies local file to remote filesystem and records both UIDs. | | `CreateLocalDir` | `remote: FolderStat` | Creates local directory and its sync record. | | `CreateRemoteDir` | `local: FolderStat` | Creates remote directory and its sync record. | | `RemoveLocal` | `local: Stat` | Deletes local path and its sync record. | | `RemoveRemote` | `remote: Stat` | Deletes remote path and its sync record. | | `MoveLocal` | `oldKey: string`, `remote: Stat` | Moves local path from `oldKey` to `key` and moves its record. | | `MoveRemote` | `oldKey: string`, `local: Stat` | Moves remote path from `oldKey` to `key` and moves its record. | | `ResolveConflict` | `local: FileStat`, `remote: FileStat`, `resolver: ConflictResolver` | Invokes resolver with both file states and sync infrastructure. | ``` -------------------------------- ### on(key, cb) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Subscribes to a typed SDK event. This allows modules to listen for specific events emitted by the SDK. ```APIDOC ## on(key, cb) ### Description Subscribes to a typed SDK event. ### Method on ### Parameters - **key** (string) - Required - The event key to subscribe to. - **cb** (function) - Required - The callback function to invoke when the event occurs. ### Returns - void ``` -------------------------------- ### Module events declaration example Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/deep-dive/architecture.md Declares the shape of values a module contributes to merged keys, used to derive the final Context, Events, Settings, and Translations types. ```typescript declare readonly events: { syncStarted: { isCancelled: Ref; trigger: string }; }; ``` -------------------------------- ### PUT /meta/{key} Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Set metadata on a database. ```APIDOC ## [PUT] /meta/{key} ### Description Set metadata on a database. ### Method PUT ### Endpoint /meta/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The metadata key. #### Request Body - **value** (any) - Required - The metadata value. ### Request Example ```ts db.setMeta('key', 'value'); ``` ### Response #### Success Response (200) No content. #### Response Example ```ts {} ``` -------------------------------- ### createRemoteFs(id?) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Creates a wrapped remote filesystem for the given backend ID. Returns an Error when the backend is missing. ```APIDOC ## createRemoteFs(id?) ### Description Creates selected wrapped remote filesystem. Returns an `Error` when the backend is missing. ### Method Function ### Signature `createRemoteFs(id?)` ### Parameters - `id` (optional) - Backend identifier. ### Returns - Remote filesystem wrapper, or `Error` if backend missing. ``` -------------------------------- ### Create symbolic link for module development Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Creates a symbolic link from the Sync Engine modules folder to your project's dist folder, enabling automatic rebuilds into the right location. ```sh ln -s /path/to/your/vault/.obsidian/plugins/sync-engine/modules /path/to/your/project/dist ``` -------------------------------- ### Request type for remote HTTP calls Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/request.md Defines the remote HTTP request function type. The URL is the first argument; omitting params performs a plain GET. Set ignoreCancellation to true to allow a request after sync cancellation, reserved for cleanup calls. ```ts type RequestParam = Omit & { body?: string | Binary; ignoreCancellation?: boolean; }; type RequestResponse = { text: () => string; bytes: () => Binary; json: () => T; // typed JSON headers: Record; status: number; }; type Request = (url: string, params?: RequestParam) => Promise; ``` -------------------------------- ### prefixWrapper(original: Fs, prefix: string): WrappedFs Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/deep-dive/file-system-wrappers.md Documentation for the prefixWrapper SDK wrapper, which exposes a directory as the root of another Fs. ```APIDOC ## prefixWrapper(original: Fs, prefix: string): WrappedFs ### Description Creates a wrapper that exposes a directory as the root of another `Fs`. The wrapper normalizes the prefix and prepends it to all file-system operations, while removing the prefix from returned paths. ### Signature `prefixWrapper(original: Fs, prefix: string): WrappedFs` ### Parameters - **original** (`Fs`) - Required - The underlying file system to wrap. - **prefix** (`string`) - Required - The directory path to expose as the root. Normalized as a unified directory key: Unicode is normalized, percent-encoded path segments are decoded, empty slash segments are removed, and a trailing `/` is added. ### Returns - **WrappedFs** - A wrapped file system that delegates operations to `original` with the normalized prefix prepended. ### Behavior - Returned stat keys, list results, and list progress paths have the prefix removed. - The wrapped directory itself is exposed as `/` and omitted from recursive list results. - A returned path outside the prefix is rejected with an error. ``` -------------------------------- ### registerSetting(entry: SettingEntry): () => boolean Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Registers a setting tree that describes a branch of the Settings tab. The top-level priority determines merge order, and numeric keys inside apply order items at each level. Returns a function to remove the registration. ```APIDOC ## registerSetting(entry: SettingEntry): () => boolean ### Description Registers a setting tree that describes a branch of the Settings tab. The top-level `priority` determines which setting is merged first; numeric keys inside `apply` order items at each level and tell Sync Engine where branches should be merged. Returns a function that removes the registration when called. ### Method registerSetting ### Endpoint ctx.registerSetting(entry: SettingEntry): () => boolean ### Parameters #### entry (SettingEntry) - Required - **priority** (number) - Required - Determines merge order of the setting tree. - **apply** (CallableOrObjectTree) - Required - Nested object or callback that defines the setting tree. ### Request Example ```ts const removeSettings = ctx.registerSetting({ apply: mySettings(ctx, this.moduleSettings), priority: 1355, }); this.cleanup.push(removeSettings); ``` ### Response #### Success Response Returns a function that removes the registered setting tree when called. #### Response Example ```ts () => boolean ``` ``` -------------------------------- ### getNamespace(local?, remote?) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Creates a storage namespace for an optional local/remote FS pair. Returns an Error when no backend is set. ```APIDOC ## getNamespace(local?, remote?) ### Description Creates storage namespace for optional local/remote FS pair. Returns an `Error` when no backend is set. ### Method Function ### Signature `getNamespace(local?, remote?)` ### Parameters - `local` (optional) - Local filesystem. - `remote` (optional) - Remote filesystem. ### Returns - Storage namespace, or `Error` if no backend set. ``` -------------------------------- ### testKit Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/debug-and-testing.md Test harness utilities for writing FS and request tests. Import from `@hesprs/sync-engine-sdk/dev`. ```APIDOC ## testKit ### Description Test harness utilities for writing FS and request tests. Import from `@hesprs/sync-engine-sdk/dev`. ### Import ```ts import { testKit } from '@hesprs/sync-engine-sdk/dev'; ``` ### Usage Example ```ts const { fs, bytes } = testKit; const harness = fs(); const content = bytes('hello'); ``` ### API #### `bytes(value: string): Binary` Convert a string to `Binary`. #### `deferred(): { promise: Promise; reject: (reason?: unknown) => void; resolve: (value: T | PromiseLike) => void; }` Create a controlled promise. #### `file(key: string, options?: { mtime?: number; size?: number; uid?: string }): FileStat` Create a `FileStat`. #### `folder(key: string): FolderStat` Create a `FolderStat`. #### `flush(turns?: number): Promise` Wait for several microtask queues to finish (default 4). #### `fs(options?: FsOptions): FsHarness` Create a stub filesystem. `control` overrides individual methods; `uid` sets `getUid()`. #### `request(control: (url: string, params: RequestParam) => MaybePromise>): RequestHarness` Wrap a response control to record calls. The control receives the same arguments as `Request` and returns response overrides. #### `stream(chunks?: Array): ReadableStream` Create a fake `ReadableStream` from an array. ### Types ```ts type FsCalls = { delete: Array; exists: Array; list: Array; mkdir: Array; move: Array<[string, string]>; read: Array<[string, FileStat]>; readStream: Array<[string, FileStat]>; stat: Array; write: Array<[string, Binary, FileStat]>; writeStream: Array<[string, FileStat]>; }; type FsOptions = { control?: Partial; uid?: string; }; type FsHarness = { calls: FsCalls; control: Fs; fs: RootFs; }; type RequestHarness = { calls: Array; request: Request; }; ``` ### `fs()` Details The `control` field accepts `Partial` — any method not overridden gets a default implementation. The returned `fs` is a `RootFs` that records all calls into `calls` and delegates to `control`. Method signatures match `RootFs` exactly, including the `stat: FileStat` parameter on `read`/`readStream`/`write`/`writeStream` and the `reporter: ListReporter` parameter on `list`. ``` -------------------------------- ### Database access points on Context Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Shows the two database access points on Context: an async IndexedDB database and a synchronous in-memory database, both backed by Uni-KV. ```typescript // Async IndexedDB database ctx.indexedDB: DatabaseAsync; // Synchronous in-memory database ctx.memoryDB: DatabaseSync; ``` -------------------------------- ### executeSync(trigger, options?) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Executes synchronization immediately. ```APIDOC ## executeSync(trigger, options?) ### Description Executes synchronization immediately. ### Method Function ### Signature `executeSync(trigger, options?)` ### Parameters - `trigger` - Trigger name. - `options` (optional) - Execution options. ### Returns - Result of sync execution. ``` -------------------------------- ### optimizeLocal(input) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Applies the selected local BatchOptimizer to the input. ```APIDOC ## optimizeLocal(input) ### Description Applies selected local `BatchOptimizer`. ### Method Function ### Signature `optimizeLocal(input)` ### Parameters - `input` - Input data for optimization. ### Returns - Optimized result. ``` -------------------------------- ### digOriginal Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/file-system.md Function to unwrap nested filesystem wrappers to the root filesystem. ```APIDOC ## digOriginal ### Description Unwraps nested wrappers to the underlying root filesystem. Use when an optimizer needs to call backend-specific methods not on the `Fs` interface (e.g., `S3Fs.batchDelete()`), combined with `instanceof` check on the returned `RootFs`. ### Signature ```ts function digOriginal(wrapped: Fs): RootFs; ``` ### Parameters - **wrapped** (`Fs`) - Required - The wrapped filesystem instance to unwrap. ### Returns - **RootFs** - The underlying root filesystem instance. ### Example ```ts import { digOriginal } from '@hesprs/sync-engine-sdk'; ``` ``` -------------------------------- ### syncStage Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Reactive current sync stage. ```APIDOC ## syncStage ### Description Reactive current sync stage. ``` -------------------------------- ### optimizeRemote(input) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Applies the selected remote BatchOptimizer to the input. ```APIDOC ## optimizeRemote(input) ### Description Applies selected remote `BatchOptimizer`. ### Method Function ### Signature `optimizeRemote(input)` ### Parameters - `input` - Input data for optimization. ### Returns - Optimized result. ``` -------------------------------- ### Run RustFS S3 server Source: https://github.com/hesprs/sync-engine/blob/main/scripts/benchmark/testing.md Runs RustFS locally on port 5005 with the specified volume directory and credentials. Requires creating the volume directory first. ```sh mkdir $HOME/Desktop/S3 RUSTFS_ADDRESS=":5005" \ RUSTFS_VOLUMES="$HOME/Desktop/S3" \ RUSTFS_ACCESS_KEY="syncengine2026" \ RUSTFS_SECRET_KEY="rustfs-test-secret" \ rustfs ``` -------------------------------- ### Monorepo structure Source: https://github.com/hesprs/sync-engine/blob/main/CONTRIBUTING.md Shows the directory layout of the Sync Engine monorepo, including docs, blueprint, packages, modules.json, and tsconfig.json. ```txt Sync Engine Monorepo ├── docs - Documentation website ├── blueprint - Internal mechanisms ├── packages │ ├── plugin - Core plugin and SDK (@hesprs/sync-engine-sdk) │ ├── shared - Shared utilities (@repo/shared) │ └── ... - Others are all official modules ├── modules.json - Official module source, records all official modules └── tsconfig.json - TypeScript config for all packages ``` -------------------------------- ### Sync Lifecycle Events Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/events.md Details about the `syncStarted` and `syncInitialized` events, including their timing and payloads. ```APIDOC ## Sync Lifecycle Events ### Description `syncStarted` fires before the file-system stacks exist; `syncInitialized` fires once per run after infrastructure initialization and before traversal, and is the only point where the sync's actual `localFs`, `remoteFs`, and `record` are published. ### Events #### `syncStarted` - **Payload**: `{ isCancelled: Ref; trigger: string }` - **Timing**: Fires before the file-system stacks exist. - **Note**: `isCancelled` is a SynthKernel `Ref` — call it as `isCancelled()` to read, or subscribe with `isCancelled.subscribe(...)`. #### `syncInitialized` - **Payload**: `Infras & { match: (path: string) => GlobMatchResult }` - **Timing**: Fires once per run after infrastructure initialization and before traversal. - **Details**: `Infras` shape is `{ localFs: Fs; remoteFs: Fs; record: RecordStore }`, documented with the [remote lister](./sync#remote-lister); `match` is the compiled [sync strategy matcher](../usage/settings#sync-strategy-rules). ``` -------------------------------- ### Register capabilities and clean up on dispose Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/registration.md Shows the recommended pattern for using Context's register* methods: store cleanup callbacks in an array and invoke them from dispose. Note that registerEvent and registerI18n are exceptions (they don't return cleanup callbacks). ```typescript export default class MyModule { private readonly cleanup: Array<() => void> = []; constructor(private readonly ctx: Context) {} start(): void { this.cleanup.push(this.ctx.registerRemoteFsWrapper(/* ... */)); this.ctx.registerI18n('en', { hello: 'Hello' }); } dispose(): void { this.cleanup.splice(0).forEach((fn) => fn()); } } ``` -------------------------------- ### Add Obsidian API dependency Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/develop-a-module.md Optional command to add the Obsidian API when the module needs it. Run it only if your module requires Obsidian API access. ```sh bun add obsidian ``` -------------------------------- ### dispatch(key, payload?) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Dispatches a typed SDK event. This allows modules to emit events that other parts of the system can listen to. ```APIDOC ## dispatch(key, payload?) ### Description Dispatches a typed SDK event. ### Method dispatch ### Parameters - **key** (string) - Required - The event key to dispatch. - **payload** (any) - Optional - The payload to pass with the event. ### Returns - void ``` -------------------------------- ### pipe Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/sync.md Reads a file from one filesystem and writes it to another under the same key, automatically selecting buffered or streaming mode based on file size. Silently succeeds if the source file does not exist. ```APIDOC ## pipe ### Description Reads a file from `from` and writes it to `to` under the same `key`. Automatically selects buffered or streaming mode based on file size (device-adaptive). Silently succeeds if the source file does not exist (swallows TOCTOU 404 / `ENOENT` errors). ### Method pipe ### Signature ```ts function pipe(options: { from: Fs; to: Fs; key: string; stat: FileStat }): Promise; ``` ### Parameters - **options** (object) - Required - An object containing: - **from** (Fs) - Required - The source filesystem. - **to** (Fs) - Required - The destination filesystem. - **key** (string) - Required - The key/path of the file to copy. - **stat** (FileStat) - Required - The file statistics. ### Example ```ts await pipe({ from: remoteFs, to: localFs, key: 'folder/note.md', stat }); ``` ### Returns Promise - Resolves when the copy is complete. ``` -------------------------------- ### RootFs interface for remote backends Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/file-system.md The RootFs interface every remote backend must implement. Keys use a unified format: '/' for root, 'note.md' or 'folder/note.md' for files, and 'folder/' or 'folder/nested/' for folders (trailing '/' required). ```ts import type { RootFs } from '@hesprs/sync-engine-sdk'; type RootFs = { getUid(): string; read(key: string, stat: FileStat): MaybePromise; readStream(key: string, stat: FileStat): MaybePromise>; write(key: string, value: Binary, stat: FileStat): MaybePromise; writeStream(key: string, value: ReadableStream, stat: FileStat): MaybePromise; delete(key: string): MaybePromise; move(oldKey: string, newKey: string): MaybePromise; mkdir(key: string, stat: FolderStat, recursive?: boolean): MaybePromise; stat(key: string): MaybePromise; exists(key: string): MaybePromise; list(key: string, reporter: ListReporter): MaybePromise>; }; ``` -------------------------------- ### decideTasks(input) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Buckets stats by strategy, invokes the registered decider per bucket, and returns the task plan. ```APIDOC ## decideTasks(input) ### Description Buckets stats by strategy, invokes the registered decider per bucket, and returns the task plan. ### Method Function ### Signature `decideTasks(input)` ### Parameters - `input` - Input stats for task decision. ### Returns - Task plan. ``` -------------------------------- ### Use label factories from context Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Uses existing label factories from context so text, colors, and translations match core settings. The render callback is a placeholder for the actual control. ```ts const { matchLabel, speedLabel } = ctx; return s(() => ({ labels: [matchLabel(), speedLabel()], name: 'Chunk size', render: (setting) => { // Render the setting control here. }, })); ``` -------------------------------- ### POST /dispose Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/storage.md Dispose the database, releasing resources. ```APIDOC ## [POST] /dispose ### Description Dispose the database, releasing resources. ### Method POST ### Endpoint /dispose ### Parameters None ### Request Example ```ts db.dispose(); ``` ### Response #### Success Response (200) No content. #### Response Example ```ts {} ``` -------------------------------- ### getLogs() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Returns formatted current logs. ```APIDOC ## getLogs() ### Description Returns formatted current logs. ### Method Function ### Signature `getLogs()` ### Returns - Formatted logs. ``` -------------------------------- ### Middleware Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/request.md Middleware wrappers for both remote and local request functions. ```APIDOC ## Middleware ### Description Request middleware wraps the request function in ascending `priority` order. There are two separate middleware systems: remote and local. ### Types ```ts type RemoteRequestMiddlewareEntry = { priority: number; apply: (request: Request) => Request | undefined; }; type LocalRequestMiddlewareEntry = { priority: number; apply: (request: VaultRequest) => VaultRequest | undefined; }; ``` ### Behavior Returning `undefined` from `apply` declines the entry at that priority. For built-in middleware (retry, rate limiter, cancellation, custom headers), see the deep dive. ``` -------------------------------- ### translate() Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md Returns the translated string for a given key, using the registered resources. Supports plain strings, snippet resources, and fragment resources. ```APIDOC ## translate(key, ...args) ### Description Returns the translated string for a given key, using the registered resources. Supports plain strings, snippet resources, and fragment resources. ### Method translate ### Parameters - **key** (string) - Required - The translation key. - **args** (any) - Optional - Arguments to pass to the snippet or fragment resource. ### Request Example ```ts const translate: Translate = ctx.translate; const label = translate('connected', 'WebDAV'); const summary = translate('files', { succeeded: 3, failed: 0 }); ``` ### Response #### Success Response Returns the translated string or DocumentFragment. #### Response Example ```ts const label = 'Connected to WebDAV.'; const summary = createFragment((frag) => { ... }); ``` ``` -------------------------------- ### s() helper Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/settings-and-ui.md SDK helper for defining a parent setting callback together with its child tree. It attaches the child tree to the parent callback, and the parent receives the complete node after all extensions have been merged. ```APIDOC ## s() helper ### Description SDK helper for defining a parent setting callback together with its child tree. It attaches the child tree to the parent callback, and the parent receives the complete node after all extensions have been merged. ### Method s ### Endpoint s(parentCallback, childTree) ### Parameters #### parentCallback (function) - Required - **self** (SettingTree) - Required - The complete node after all extensions have been merged. - Returns a SettingDefinitionItem. #### childTree (object) - Required - Numeric keys map to child callbacks or nested trees. ### Request Example ```ts import { s } from '@hesprs/sync-engine-sdk'; export default function mySettings( ctx: Context, settings: { enabled: boolean }, ): CallableOrObjectTree { return { 2000: s( (self) => ({ heading: ctx.translate('mySettings'), items: Object.values(self).map((node) => node(node) as SettingGroupItem), type: 'group', }), { 1000: s(() => ({ control: { key: 'enabled', type: 'toggle' }, name: ctx.translate('enabled'), })), }, ), }; } ``` ### Response #### Success Response Returns a CallableOrObjectTree that can be passed to `registerSetting`. #### Response Example ```ts { 2000: s( (self) => ({ heading: ctx.translate('mySettings'), items: Object.values(self).map((node) => node(node) as SettingGroupItem), type: 'group', }), { 1000: s(() => ({ control: { key: 'enabled', type: 'toggle' }, name: ctx.translate('enabled'), })), }, ), } ``` ``` -------------------------------- ### addCommand(cmd) Source: https://github.com/hesprs/sync-engine/blob/main/docs/src/pages/en/development/miscellaneous.md Registers an Obsidian command and returns it. This method allows modules to add custom commands to Obsidian. ```APIDOC ## addCommand(cmd) ### Description Registers an Obsidian command and returns it. ### Method addCommand ### Parameters - **cmd** (Command) - Required - The command object to register. ### Returns - The registered command. ```