init static method
Initialize vault: creates WS channel and connects.
Implementation
static Future<Vault> init(VaultConfig config) async {
final baseUri = Uri.parse(config.serverUrl);
final serializer = MsgpackSerializer();
// Deterministic AES-256 key: SHA-256(projectId:apiKey) = 32 bytes
final keyBytes = (await Sha256().hash(
utf8.encode('aquabase:${config.projectId}:${config.apiKey}'),
)).bytes;
final crypto = Aes256GcmCrypto();
final secretKey = SecretKey(keyBytes);
CacheStrategy? cache;
String? cacheDir;
if (config.enableCache) {
final provider =
config.directoryProvider ?? () => getApplicationDocumentsDirectory();
final appDir = await provider();
final cacheId = config.projectId;
cacheDir = '${appDir.path}/aquabase_cache/$cacheId';
cache = await CompactCache.create(cacheDir);
}
final wsScheme = baseUri.scheme == 'https' ? 'wss' : 'ws';
final wsUri = baseUri.replace(
scheme: wsScheme,
path: '/sync',
queryParameters: {'key': config.apiKey},
);
final ws = WsChannel(wsUri: wsUri, jwt: config.jwt);
await ws.connect();
final vault = Vault._(
serializer: serializer,
ws: ws,
crypto: crypto,
cache: cache,
secretKey: secretKey,
encryptedGlobal: config.encrypted,
);
ws.onReconnected = () async {
vault._flushOfflineQueues();
// Update schema in background on reconnects
vault._fetchServerSchemaWss().catchError((_) {});
};
// SmartCache if disk cache available
if (cache != null && cacheDir != null) {
vault._smartCache = SmartCache(
cache: cache,
queueDir: cacheDir,
wsChannel: ws,
enableCompression: false,
);
// Wait for the persisted queue to be loaded from disk before flushing.
await vault._smartCache!.ready;
}
// Flush offline queue
if (vault._smartCache != null) {
await vault._smartCache!.flushQueue();
}
// Load server index schema so all SDKs share the same indexed fields
try {
await vault._ws.connect();
await vault._fetchServerSchemaWss();
} catch (_) {
// Offline fallback
}
return vault;
}