@exmg/capacitor-file-sync
v0.0.1
Published
Library for Capacitor apps to keep files in sync with a remote host
Readme
@exmg/capacitor-file-sync
Keeps a local directory in a Capacitor app in sync with files on a remote host.
- A remote manifest (
index.json) lists the files, grouped into collections. Each collection syncs on its own. - A sync downloads the files that are new or have a different version than the local copy.
- Files can ship with the app (bundled) so they're available offline from the first launch. Downloads replace them when the remote version changes.
- A failed or stopped sync never breaks anything: the previous copy stays usable until the new one has fully downloaded.
Installation
bun add @exmg/capacitor-file-sync @capacitor/filesystem @capacitor/file-transfer
bunx cap syncPeer dependencies: @capacitor/core 8, @capacitor/filesystem 8 and @capacitor/file-transfer 2.
Enable native HTTP
The manifest is loaded with fetch. On iOS and Android the web view's origin differs from your host, so without CORS headers on the host the request is blocked. Enable CapacitorHttp to route fetch through native HTTP:
// capacitor.config.ts
const config: CapacitorConfig = {
// ...
plugins: {
CapacitorHttp: { enabled: true },
},
};File downloads use @capacitor/file-transfer, which runs natively and isn't affected by CORS.
Setting up the remote host
Host an index.json at your base URL, for example https://cdn.example.com/content/index.json. Its keys are collection names, each with a list of files:
{
"wiki": [
{ "id": "birds", "url": "wiki/birds.txt", "version": "05a066c1f1ef..." },
{ "id": "trees", "url": "wiki/trees.txt", "version": "dfd6d44cbef7..." }
],
"images": [{ "id": "logo", "url": "https://images.example.com/logo.png", "version": "3" }]
}| Field | Description |
| --------- | -------------------------------------------------------------------------------------------- |
| id | Identifies the file within its collection, across versions. |
| url | Absolute URL, or relative to the base URL. |
| version | Any string; only compared for equality. A hash of the contents (such as SHA-256) works well. |
The remote manifest is the source of truth: a local copy whose version differs from the manifest is replaced on the next sync. Files removed from the manifest are not synced anymore.
Files under the base URL are stored with the same relative path as on the host (wiki/birds.txt). Files elsewhere are stored as {collection}/{id}{extension} (images/logo.png).
Bundling files with the app (optional)
To have files available before the first sync, ship them in the web assets under the configured path, together with an index.json in the same format. In the bundled manifest, url is the path relative to path.
public/
content/ ← FileSyncConfig.path = 'content'
index.json
wiki/
birds.txt
trees.txt{
"wiki": [
{ "id": "birds", "url": "wiki/birds.txt", "version": "05a066c1f1ef..." },
{ "id": "trees", "url": "wiki/trees.txt", "version": "dfd6d44cbef7..." }
]
}Use the same ids and versions as the remote manifest. A bundled file whose version matches the remote one isn't downloaded. An easy way to get this right is to copy the remote index.json and files into the app at build time.
Without bundled files, leave the directory out; every file is downloaded on the first sync.
Usage
Create an instance
Create one instance per base URL and path, and reuse it throughout the app:
import { createFileSync } from '@exmg/capacitor-file-sync';
import { Directory } from '@capacitor/filesystem';
export const fileSync = createFileSync({
baseUrl: 'https://cdn.example.com/content/',
path: 'content',
directory: Directory.Library, // default
headers: { Authorization: `Bearer ${token}` }, // optional, sent with every request
});| Option | Description |
| ----------- | -------------------------------------------------------------------------------------- |
| baseUrl | Where index.json is fetched from. Relative file URLs are resolved against it. |
| path | Sub path for both the bundled files (web-relative) and the downloads (in directory). |
| directory | Filesystem directory for the downloads. Defaults to Directory.Library. |
| headers | Extra headers for the manifest request and the downloads. |
Set downloadOptions to change the download options for every sync. The downloadOptions passed to sync override them per option.
Sync a collection
const result = await fileSync.sync({ collection: 'wiki' });
if (result.status === 'stale') {
console.warn('Some files could not be downloaded', result.failed);
}sync resolves once all downloads have finished, even when some of them failed. It only rejects when the manifest can't be fetched or doesn't contain the collection, or when the collection is already syncing.
| Option | Description |
| ----------------- | --------------------------------------------------------------------------------------------------- |
| collection | The collection to sync. |
| downloadOptions | Download options for this sync. Override those of createFileSync per option. |
Download options
await fileSync.sync({ collection: 'wiki', downloadOptions: { maxConcurrentDownloads: 1 } });| Option | Default | Description |
| ------------------------ | ------- | ---------------------------------------------------------------------------------------------------------------- |
| maxConcurrentDownloads | 3 | Downloads that run at the same time. |
| maxRetries | 2 | Retries per file after a network, timeout or server error. The delay starts at 1 second and doubles every retry. |
| downloadTimeoutMs | 60000 | Connect and read timeout per download. |
Before downloading, a sync removes downloaded copies made redundant by a bundled copy with the same version, for example after an app update that bundles newer files.
Preview a sync
To check whether there are updates without downloading anything, for example to ask the user first:
const preview = await fileSync.previewSync('wiki');
if (preview.status === 'stale') {
const size = preview.totalBytes === undefined ? '' : ` (${preview.totalBytes} bytes)`;
if (confirm(`Download ${preview.files.pending.length} updated files${size}?`)) {
await fileSync.sync({ collection: 'wiki' });
}
}Use the synced files
The result of sync and previewSync contains files.resolved: one usable copy per file, in manifest order. That's the up-to-date copy, or a stale one if the update hasn't been downloaded yet.
A LocalFile's path is relative to the directory of its source. Get that directory with getDirectory, and for downloaded files convert the native URI so the web view can load it:
import { Capacitor } from '@capacitor/core';
import type { LocalFile } from '@exmg/capacitor-file-sync';
const directories = {
bundled: await fileSync.getDirectory('bundled'), // 'content'
downloaded: Capacitor.convertFileSrc(await fileSync.getDirectory('downloaded')), // 'capacitor://localhost/_capacitor_file_/…'
};
function toSrc(file: LocalFile): string {
return `${directories[file.source]}/${file.path}`;
}
const { files } = await fileSync.previewSync('wiki');
for (const file of files.resolved) {
console.log(file.id, toSrc(file));
}To read a downloaded file's contents natively instead, use Filesystem.readFile with the configured directory and `${path}/${file.path}`.
files also lists upToDate, pending (remote files without a local copy of their version) and stale (older local copies of pending files).
To work offline, without fetching the remote manifest, read the local manifests with getManifest('bundled') and getManifest('downloaded').
Follow progress
Listen to events to show progress. Listeners receive events of all collections, so filter on collection if needed. addListener returns a function that removes the listener.
const removeListeners = [
fileSync.addListener('syncStarted', ({ collection, files, totalBytes }) => {
console.log(`Syncing ${collection}: ${files.pending.length} files, ${totalBytes ?? '?'} bytes`);
}),
fileSync.addListener('downloadProgress', ({ file, queuePosition, queueLength, bytesDownloaded, totalBytes }) => {
console.log(`${queuePosition + 1}/${queueLength} ${file.id}: ${bytesDownloaded}/${totalBytes ?? '?'}`);
}),
fileSync.addListener('downloaded', (file) => console.log(`${file.id} is ready at ${file.path}`)),
fileSync.addListener('downloadFailed', ({ download }) => console.warn(download.file.id, download.error)),
fileSync.addListener('syncCompleted', (result) => console.log(`${result.collection}: ${result.status}`)),
];
// Later
for (const remove of removeListeners) remove();| Event | When |
| ------------------ | ------------------------------------------------------------------------------ |
| syncStarted | The manifest is fetched, before downloading. Payload: what will be downloaded. |
| downloadStarted | A file starts downloading (once per file, not per retry). |
| downloadProgress | Bytes were received. Restarts from 0 on a retry. |
| downloadRetry | An attempt failed and will be retried after delayMs. |
| downloaded | A file is downloaded and usable. |
| downloadFailed | A file failed after all retries. The sync continues with the other files. |
| syncCompleted | The sync finished, also when downloads failed or the sync was stopped. |
| syncFailed | The manifest couldn't be used. The sync call rejects with the same error. |
Stop a sync
await fileSync.stopSync('wiki');No new downloads start; running ones finish. The sync call resolves with the files that weren't downloaded in failed, with error code aborted. Use isSyncing(collection) to check whether a sync is running, and getSyncStatus(collection) for the status of the last preview or sync (unknown, synced or stale).
Free up storage
// Remove downloads that are redundant because a bundled copy has the same version, or the remote one.
const { removed } = await fileSync.cleanUpDownloads('wiki');
// Remove all downloads of a collection, falling back to the bundled files. Works offline.
await fileSync.removeDownloads('wiki');Both reject while the collection is syncing.
Errors
Failures are reported as a SyncError with a code:
| Code | Meaning |
| ------------------ | --------------------------------------------------------------------------- |
| network | The request couldn't be made. |
| timeout | A download exceeded downloadTimeoutMs. |
| http | The server responded with an error; see status. |
| filesystem | Reading or writing on the device failed. |
| invalid-manifest | index.json isn't valid, or doesn't contain the collection. |
| aborted | The download didn't start because of stopSync. |
| sync-in-progress | sync (or a clean-up) was called while the collection was already syncing. |
try {
await fileSync.sync({ collection: 'wiki' });
} catch (error) {
const { code, message } = error as SyncError;
if (code === 'sync-in-progress') return;
console.error(code, message);
}Downloads are retried after network and timeout errors, and HTTP 5xx, 408 and 429 responses.
Example app
examples/example-app is a Capacitor app that exercises the whole API against test data in its own web assets. See its README.
Development
bun install
bun run typecheck
bun run lint
bun run test
bun run build