local-lite 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -95,6 +95,7 @@ For an application-level upgrade checklist or AI-assisted code review, see the
95
95
  The package ships [Agent Skills](./skills) that AI coding assistants can load:
96
96
  * `local-lite-setup`: Multi-platform setup (Expo, Web, Node) and client initialization.
97
97
  * `local-lite-auth`: Zero-backend SQLite authentication, PBKDF2 crypto, lockout, reset tokens, and OAuth.
98
+ * `local-lite-server`: Framework-neutral REST API routing, route params, middleware pipelines, and single fetch() dispatcher.
98
99
  * `local-lite-backups`: Cloud backups (OneDrive, Google Drive), AES-256-GCM database encryption, and restore.
99
100
  * `local-lite-schema`: Declarative cascading deletions (`onDelete`), append-only migrations, and FTS5 search.
100
101
  * `local-lite-storage`: Blob and file management, ExpoFileDriver, and cloud storage bucket sync.
@@ -104,8 +105,10 @@ The package ships [Agent Skills](./skills) that AI coding assistants can load:
104
105
  * `local-lite-upgrade`: Migration checklist and breaking change reviews across version upgrades.
105
106
 
106
107
  ```bash
107
- npx local-lite install-skills # Copilot: .github/skills
108
- npx local-lite install-skills --target claude # Claude Code: .claude/skills
108
+ npx local-lite install-skills # Copilot: .github/skills
109
+ npx local-lite install-skills --target claude # Claude Code: .claude/skills
110
+ npx local-lite install-skills --target antigravity # Antigravity / Gemini: .gemini/skills
111
+ npx local-lite install-skills --target cursor # Cursor: .cursor/skills
109
112
  npx local-lite install-skills --dir path/to/dir --force
110
113
  ```
111
114
 
@@ -1,62 +1,66 @@
1
1
  #!/usr/bin/env node
2
- import { cp, mkdir, readdir } from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
-
6
- const skillsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills');
7
- const targets = {
8
- copilot: '.github/skills',
9
- claude: '.claude/skills',
10
- };
11
-
12
- const usage = `Usage: local-lite install-skills [--target copilot|claude] [--dir <path>] [--force]
13
-
14
- Copies the bundled AI skills into your project.
15
- --target copilot (default, .github/skills) or claude (.claude/skills)
16
- --dir custom destination directory (overrides --target)
17
- --force overwrite existing skill files`;
18
-
19
- function parseArgs(argv) {
20
- const options = { target: 'copilot', dir: undefined, force: false };
21
- for (let i = 0; i < argv.length; i++) {
22
- const arg = argv[i];
23
- if (arg === '--force') options.force = true;
24
- else if (arg === '--target') options.target = argv[++i];
25
- else if (arg === '--dir') {
26
- options.dir = argv[++i];
27
- if (!options.dir) throw new Error('--dir requires a path.');
28
- } else throw new Error(`Unknown option: ${arg}`);
29
- }
30
- if (!options.dir && !targets[options.target]) {
31
- throw new Error(`Unknown target "${options.target}". Use copilot or claude.`);
32
- }
33
- return options;
34
- }
35
-
36
- async function installSkills(options) {
37
- const destination = path.resolve(process.cwd(), options.dir ?? targets[options.target]);
38
- await mkdir(destination, { recursive: true });
39
- const entries = await readdir(skillsRoot, { withFileTypes: true });
40
- for (const entry of entries.filter((item) => item.isDirectory())) {
41
- await cp(path.join(skillsRoot, entry.name), path.join(destination, entry.name), {
42
- recursive: true,
43
- force: options.force,
44
- errorOnExist: false,
45
- });
46
- console.log(`Installed ${entry.name} -> ${path.join(destination, entry.name)}`);
47
- }
48
- }
49
-
50
- const [command, ...rest] = process.argv.slice(2);
51
- try {
52
- if (command === 'install-skills') {
53
- await installSkills(parseArgs(rest));
54
- } else {
55
- console.log(usage);
56
- process.exitCode = command && command !== '--help' && command !== '-h' ? 1 : 0;
57
- }
58
- } catch (error) {
59
- console.error(error instanceof Error ? error.message : error);
60
- console.error(usage);
61
- process.exitCode = 1;
62
- }
2
+ import { cp, mkdir, readdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const skillsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills');
7
+ const targets = {
8
+ copilot: '.github/skills',
9
+ claude: '.claude/skills',
10
+ antigravity: '.gemini/skills',
11
+ gemini: '.gemini/skills',
12
+ cursor: '.cursor/skills',
13
+ agent: '.agent/skills',
14
+ };
15
+
16
+ const usage = `Usage: local-lite install-skills [--target copilot|claude|antigravity|cursor|agent] [--dir <path>] [--force]
17
+
18
+ Copies the bundled AI skills into your project.
19
+ --target copilot (default, .github/skills), claude (.claude/skills), antigravity (.gemini/skills), cursor (.cursor/skills), agent (.agent/skills)
20
+ --dir custom destination directory (overrides --target)
21
+ --force overwrite existing skill files`;
22
+
23
+ function parseArgs(argv) {
24
+ const options = { target: 'copilot', dir: undefined, force: false };
25
+ for (let i = 0; i < argv.length; i++) {
26
+ const arg = argv[i];
27
+ if (arg === '--force') options.force = true;
28
+ else if (arg === '--target') options.target = argv[++i];
29
+ else if (arg === '--dir') {
30
+ options.dir = argv[++i];
31
+ if (!options.dir) throw new Error('--dir requires a path.');
32
+ } else throw new Error(`Unknown option: ${arg}`);
33
+ }
34
+ if (!options.dir && !targets[options.target]) {
35
+ throw new Error(`Unknown target "${options.target}". Supported: ${Object.keys(targets).join(', ')}.`);
36
+ }
37
+ return options;
38
+ }
39
+
40
+ async function installSkills(options) {
41
+ const destination = path.resolve(process.cwd(), options.dir ?? targets[options.target]);
42
+ await mkdir(destination, { recursive: true });
43
+ const entries = await readdir(skillsRoot, { withFileTypes: true });
44
+ for (const entry of entries.filter((item) => item.isDirectory())) {
45
+ await cp(path.join(skillsRoot, entry.name), path.join(destination, entry.name), {
46
+ recursive: true,
47
+ force: options.force,
48
+ errorOnExist: false,
49
+ });
50
+ console.log(`Installed ${entry.name} -> ${path.join(destination, entry.name)}`);
51
+ }
52
+ }
53
+
54
+ const [command, ...rest] = process.argv.slice(2);
55
+ try {
56
+ if (command === 'install-skills') {
57
+ await installSkills(parseArgs(rest));
58
+ } else {
59
+ console.log(usage);
60
+ process.exitCode = command && command !== '--help' && command !== '-h' ? 1 : 0;
61
+ }
62
+ } catch (error) {
63
+ console.error(error instanceof Error ? error.message : error);
64
+ console.error(usage);
65
+ process.exitCode = 1;
66
+ }
@@ -1,4 +1,4 @@
1
- import { RemoteDBAdapter } from './index.js';
1
+ import { RemoteAutomationJob, RemoteBackupArchive, RemoteDBAdapter } from './index.js';
2
2
  import { DeltaChanges, SyncOperation, PushResult } from '../../core/types.js';
3
3
  import { SyncLogger, CustomLogger, LogLevel } from '../../utils/logger.js';
4
4
  import { createConvexStorageUploader, ConvexStorageUploaderOptions, ConvexStorageUploaderInstance } from '../../storage/convex.js';
@@ -79,5 +79,29 @@ export declare class ConvexRemoteAdapter implements RemoteDBAdapter {
79
79
  * Connects local-lite offline blob/file storage directly to Convex File Storage.
80
80
  */
81
81
  createStorageUploader(options?: ConvexStorageUploaderOptions): ConvexStorageUploaderInstance;
82
+ /**
83
+ * Invokes a remote Convex action or mutation.
84
+ */
85
+ call<T = any>(functionName: string, args?: any): Promise<T>;
86
+ /**
87
+ * Queries a remote Convex query function.
88
+ */
89
+ queryRemote<T = any>(queryName: string, args?: any): Promise<T>;
90
+ /**
91
+ * Lists automated cron jobs configured on Convex.
92
+ */
93
+ listAutomations(): Promise<RemoteAutomationJob[]>;
94
+ /**
95
+ * Enables or disables an automated cron job on Convex.
96
+ */
97
+ setAutomationEnabled(jobId: string, enabled: boolean): Promise<void>;
98
+ /**
99
+ * Lists cloud backup archives stored on Convex.
100
+ */
101
+ listBackups(): Promise<RemoteBackupArchive[]>;
102
+ /**
103
+ * Gets a direct download URL for a file stored on Convex.
104
+ */
105
+ getDownloadUrl(fileIdOrKey: string): Promise<string | null>;
82
106
  }
83
107
  export { createConvexStorageUploader, type ConvexStorageUploaderOptions, type ConvexStorageUploaderInstance, };
@@ -240,5 +240,64 @@ class ConvexRemoteAdapter {
240
240
  createStorageUploader(options = {}) {
241
241
  return (0, convex_js_1.createConvexStorageUploader)(this.client, options);
242
242
  }
243
+ /**
244
+ * Invokes a remote Convex action or mutation.
245
+ */
246
+ async call(functionName, args = {}) {
247
+ if (typeof this.client?.action === 'function') {
248
+ try {
249
+ return await this.client.action(functionName, args);
250
+ }
251
+ catch (err) {
252
+ if (typeof this.client?.mutation === 'function' && err?.message?.includes?.('not an action')) {
253
+ return await this.client.mutation(functionName, args);
254
+ }
255
+ throw err;
256
+ }
257
+ }
258
+ if (typeof this.client?.mutation === 'function') {
259
+ return await this.client.mutation(functionName, args);
260
+ }
261
+ throw new Error('Convex client does not support action or mutation execution.');
262
+ }
263
+ /**
264
+ * Queries a remote Convex query function.
265
+ */
266
+ async queryRemote(queryName, args = {}) {
267
+ if (typeof this.client?.query === 'function') {
268
+ return await this.client.query(queryName, args);
269
+ }
270
+ throw new Error('Convex client does not support query execution.');
271
+ }
272
+ /**
273
+ * Lists automated cron jobs configured on Convex.
274
+ */
275
+ async listAutomations() {
276
+ return this.queryRemote('functions/automations:listMine', {});
277
+ }
278
+ /**
279
+ * Enables or disables an automated cron job on Convex.
280
+ */
281
+ async setAutomationEnabled(jobId, enabled) {
282
+ return this.call('functions/automations:setEnabled', { jobId, enabled });
283
+ }
284
+ /**
285
+ * Lists cloud backup archives stored on Convex.
286
+ */
287
+ async listBackups() {
288
+ return this.queryRemote('functions/convexBackups:listMyBackups', {});
289
+ }
290
+ /**
291
+ * Gets a direct download URL for a file stored on Convex.
292
+ */
293
+ async getDownloadUrl(fileIdOrKey) {
294
+ if (typeof this.client?.query === 'function') {
295
+ try {
296
+ return await this.client.query('functions/convexBackups:getDownloadUrl', { storageId: fileIdOrKey });
297
+ }
298
+ catch { }
299
+ }
300
+ return null;
301
+ }
243
302
  }
244
303
  exports.ConvexRemoteAdapter = ConvexRemoteAdapter;
@@ -1,4 +1,20 @@
1
1
  import { SyncOperation, DeltaChanges, PushResult } from '../../core/types.js';
2
+ export interface RemoteAutomationJob {
3
+ id: string;
4
+ name: string;
5
+ description?: string;
6
+ enabled: boolean;
7
+ locked?: boolean;
8
+ }
9
+ export interface RemoteBackupArchive {
10
+ createdAt: number;
11
+ status: string;
12
+ fileName?: string;
13
+ sizeBytes?: number;
14
+ recordCount?: number;
15
+ error?: string;
16
+ downloadUrl: string | null;
17
+ }
2
18
  export interface RemoteDBAdapter {
3
19
  pushChanges(operations: SyncOperation[]): Promise<boolean | PushResult>;
4
20
  /** Return a complete batch through timestamp; reject on partial failure. Supports optional scope for data filtering. */
@@ -6,6 +22,18 @@ export interface RemoteDBAdapter {
6
22
  /** Live events do not advance the durable pull checkpoint; return a cleanup function. */
7
23
  subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
8
24
  setSyncScope?(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
25
+ /** Call a remote cloud action/function/RPC */
26
+ call?<T = any>(functionName: string, args?: any): Promise<T>;
27
+ /** Query a remote function or view */
28
+ queryRemote?<T = any>(queryName: string, args?: any): Promise<T>;
29
+ /** List cloud automated cron jobs */
30
+ listAutomations?(): Promise<RemoteAutomationJob[]>;
31
+ /** Enable or disable a cloud automated cron job */
32
+ setAutomationEnabled?(jobId: string, enabled: boolean): Promise<void>;
33
+ /** List remote cloud backup archive files */
34
+ listBackups?(): Promise<RemoteBackupArchive[]>;
35
+ /** Get a public or signed download URL for a cloud file/backup */
36
+ getDownloadUrl?(fileIdOrKey: string): Promise<string | null>;
9
37
  }
10
38
  export * from './supabase.js';
11
39
  export * from './demo.js';
@@ -1,5 +1,5 @@
1
1
  import type { SupabaseClient } from '@supabase/supabase-js';
2
- import { RemoteDBAdapter } from './index.js';
2
+ import { RemoteAutomationJob, RemoteBackupArchive, RemoteDBAdapter } from './index.js';
3
3
  import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
4
4
  import { SyncLogger, CustomLogger, LogLevel } from '../../utils/logger.js';
5
5
  import { createSupabaseStorageUploader, type SupabaseStorageUploaderOptions, type SupabaseStorageUploaderInstance } from '../../storage/supabase.js';
@@ -129,5 +129,29 @@ export declare class SupabaseRemoteAdapter implements RemoteDBAdapter {
129
129
  * Connects local-lite offline blob/file storage directly to Supabase Storage.
130
130
  */
131
131
  createStorageUploader(options: SupabaseStorageUploaderOptions): SupabaseStorageUploaderInstance;
132
+ /**
133
+ * Invokes a Supabase Edge Function or Postgres RPC function.
134
+ */
135
+ call<T = any>(functionName: string, args?: any): Promise<T>;
136
+ /**
137
+ * Queries a remote Postgres RPC or view.
138
+ */
139
+ queryRemote<T = any>(queryName: string, args?: any): Promise<T>;
140
+ /**
141
+ * Lists automated cron jobs configured on Supabase.
142
+ */
143
+ listAutomations(): Promise<RemoteAutomationJob[]>;
144
+ /**
145
+ * Enables or disables an automated cron job on Supabase.
146
+ */
147
+ setAutomationEnabled(jobId: string, enabled: boolean): Promise<void>;
148
+ /**
149
+ * Lists cloud backup archives stored on Supabase Storage.
150
+ */
151
+ listBackups(): Promise<RemoteBackupArchive[]>;
152
+ /**
153
+ * Gets a signed download URL for a file stored on Supabase Storage.
154
+ */
155
+ getDownloadUrl(fileIdOrKey: string): Promise<string | null>;
132
156
  }
133
157
  export { SupabaseRemoteAdapter as SupabaseAdapter, createSupabaseStorageUploader, type SupabaseStorageUploaderOptions, type SupabaseStorageUploaderInstance, };
@@ -650,6 +650,96 @@ class SupabaseRemoteAdapter {
650
650
  createStorageUploader(options) {
651
651
  return (0, supabase_js_1.createSupabaseStorageUploader)(this.getClient(), options);
652
652
  }
653
+ /**
654
+ * Invokes a Supabase Edge Function or Postgres RPC function.
655
+ */
656
+ async call(functionName, args = {}) {
657
+ const client = this.getClient();
658
+ if (!client)
659
+ throw new Error('Supabase client is not available.');
660
+ if (typeof client.functions?.invoke === 'function') {
661
+ try {
662
+ const { data, error } = await client.functions.invoke(functionName, { body: args });
663
+ if (!error)
664
+ return data;
665
+ if (error?.status !== 404 && !error?.message?.includes?.('not found')) {
666
+ throw error;
667
+ }
668
+ }
669
+ catch (err) {
670
+ if (!err?.message?.includes?.('not found')) {
671
+ // If RPC is available, fall through and try RPC
672
+ if (typeof client.rpc !== 'function')
673
+ throw err;
674
+ }
675
+ }
676
+ }
677
+ if (typeof client.rpc === 'function') {
678
+ const { data, error } = await client.rpc(functionName, args);
679
+ if (error)
680
+ throw error;
681
+ return data;
682
+ }
683
+ throw new Error('Supabase client does not support functions or rpc invocation.');
684
+ }
685
+ /**
686
+ * Queries a remote Postgres RPC or view.
687
+ */
688
+ async queryRemote(queryName, args = {}) {
689
+ const client = this.getClient();
690
+ if (typeof client?.rpc === 'function') {
691
+ const { data, error } = await client.rpc(queryName, args);
692
+ if (error)
693
+ throw error;
694
+ return data;
695
+ }
696
+ throw new Error('Supabase client does not support rpc queries.');
697
+ }
698
+ /**
699
+ * Lists automated cron jobs configured on Supabase.
700
+ */
701
+ async listAutomations() {
702
+ return this.call('list_automations', {});
703
+ }
704
+ /**
705
+ * Enables or disables an automated cron job on Supabase.
706
+ */
707
+ async setAutomationEnabled(jobId, enabled) {
708
+ return this.call('set_automation_enabled', { job_id: jobId, enabled });
709
+ }
710
+ /**
711
+ * Lists cloud backup archives stored on Supabase Storage.
712
+ */
713
+ async listBackups() {
714
+ try {
715
+ const client = this.getClient();
716
+ if (typeof client?.storage?.from === 'function') {
717
+ const { data, error } = await client.storage.from('backups').list();
718
+ if (!error && Array.isArray(data)) {
719
+ return data.map((file) => ({
720
+ createdAt: new Date(file.created_at || file.updated_at || Date.now()).getTime(),
721
+ status: 'succeeded',
722
+ fileName: file.name,
723
+ sizeBytes: file.metadata?.size,
724
+ downloadUrl: null,
725
+ }));
726
+ }
727
+ }
728
+ }
729
+ catch { }
730
+ return [];
731
+ }
732
+ /**
733
+ * Gets a signed download URL for a file stored on Supabase Storage.
734
+ */
735
+ async getDownloadUrl(fileIdOrKey) {
736
+ const client = this.getClient();
737
+ if (typeof client?.storage?.from === 'function') {
738
+ const { data } = await client.storage.from('backups').createSignedUrl(fileIdOrKey, 3600);
739
+ return data?.signedUrl ?? null;
740
+ }
741
+ return null;
742
+ }
653
743
  }
654
744
  exports.SupabaseRemoteAdapter = SupabaseRemoteAdapter;
655
745
  exports.SupabaseAdapter = SupabaseRemoteAdapter;
@@ -90,7 +90,19 @@ export interface LocalAuthEngineOptions {
90
90
  * Shared SessionManager instance or options to configure internal SessionManager.
91
91
  */
92
92
  session?: SessionManager | SessionManagerOptions;
93
+ /**
94
+ * Optional remote authentication handler to exchange local sessions for remote sync provider tokens.
95
+ */
96
+ remoteAuthHandler?: RemoteAuthHandler;
97
+ }
98
+ export interface RemoteAuthExchangeContext<TMetadata = any> {
99
+ user: LocalUser<TMetadata>;
100
+ session: SessionRecord<LocalUser<TMetadata>>;
93
101
  }
102
+ export type RemoteAuthHandler<TMetadata = any> = (context: RemoteAuthExchangeContext<TMetadata>) => Promise<{
103
+ token: string;
104
+ [key: string]: any;
105
+ } | null>;
94
106
  export interface SignUpOptions<TMetadata = Record<string, any>> {
95
107
  id?: string;
96
108
  email: string;
@@ -198,7 +210,27 @@ export declare class LocalAuthEngine {
198
210
  private minPasswordLength;
199
211
  private customPasswordValidator?;
200
212
  private sessionManager;
201
- constructor(db: DBExecutable, sessionOrManager?: SessionManager | SessionManagerOptions, events?: EventEmitter | undefined, options?: LocalAuthEngineOptions);
213
+ private remoteAuthHandler?;
214
+ constructor(db: DBExecutable, sessionOrManager?: SessionManager | SessionManagerOptions | LocalAuthEngineOptions, events?: EventEmitter | undefined, options?: LocalAuthEngineOptions);
215
+ /**
216
+ * Registers a pluggable remote authentication exchange handler.
217
+ */
218
+ setRemoteAuthHandler(handler: RemoteAuthHandler): void;
219
+ /**
220
+ * Gets the configured remote authentication exchange handler.
221
+ */
222
+ getRemoteAuthHandler(): RemoteAuthHandler | undefined;
223
+ /**
224
+ * Triggers token exchange with the registered remote sync provider for the active session.
225
+ */
226
+ exchangeRemoteAuth(): Promise<{
227
+ token: string;
228
+ [key: string]: any;
229
+ } | null>;
230
+ /**
231
+ * Retrieves the cached remote sync authentication token from the active session.
232
+ */
233
+ getRemoteAuthToken(): Promise<string | null>;
202
234
  /**
203
235
  * Retrieves the underlying SessionManager instance.
204
236
  */
@@ -10,6 +10,7 @@ exports.mapStoredUserRow = mapStoredUserRow;
10
10
  const pbkdf2_js_1 = require("@noble/hashes/pbkdf2.js");
11
11
  const sha2_js_1 = require("@noble/hashes/sha2.js");
12
12
  const utils_js_1 = require("@noble/hashes/utils.js");
13
+ const event_emitter_js_1 = require("../reactive/event-emitter.js");
13
14
  const uuid_js_1 = require("../utils/uuid.js");
14
15
  const sql_js_1 = require("../utils/sql.js");
15
16
  const generator_js_1 = require("../keys/generator.js");
@@ -184,27 +185,83 @@ class LocalAuthEngine {
184
185
  minPasswordLength;
185
186
  customPasswordValidator;
186
187
  sessionManager;
188
+ remoteAuthHandler;
187
189
  constructor(db, sessionOrManager, events, options = {}) {
188
190
  this.db = db;
189
191
  this.events = events;
190
- this.usersTable = options.usersTable || exports.DEFAULT_USERS_TABLE;
191
- this.tokensTable = options.tokensTable || exports.DEFAULT_USER_TOKENS_TABLE;
192
+ let resolvedOptions = options;
193
+ let resolvedSession = sessionOrManager instanceof session_js_1.SessionManager ? sessionOrManager : undefined;
194
+ let resolvedEvents = events;
195
+ if (sessionOrManager && !(sessionOrManager instanceof session_js_1.SessionManager)) {
196
+ if ('usersTable' in sessionOrManager ||
197
+ 'iterations' in sessionOrManager ||
198
+ 'remoteAuthHandler' in sessionOrManager ||
199
+ 'maxFailedAttempts' in sessionOrManager) {
200
+ resolvedOptions = sessionOrManager;
201
+ resolvedSession = sessionOrManager.session;
202
+ }
203
+ else {
204
+ resolvedSession = sessionOrManager;
205
+ }
206
+ }
207
+ this.events = resolvedEvents || new event_emitter_js_1.EventEmitter();
208
+ this.usersTable = resolvedOptions.usersTable || exports.DEFAULT_USERS_TABLE;
209
+ this.tokensTable = resolvedOptions.tokensTable || exports.DEFAULT_USER_TOKENS_TABLE;
192
210
  this.sqlUsersTable = (0, sql_js_1.escapeIdentifier)(this.usersTable);
193
211
  this.sqlTokensTable = (0, sql_js_1.escapeIdentifier)(this.tokensTable);
194
- this.algorithm = options.algorithm || exports.DEFAULT_PASSWORD_ALGORITHM;
195
- this.iterations = options.iterations || exports.DEFAULT_PASSWORD_ITERATIONS;
196
- this.saltBytes = options.saltBytes || exports.DEFAULT_SALT_BYTES;
197
- this.maxFailedAttempts = options.maxFailedAttempts ?? exports.DEFAULT_LOCKOUT_ATTEMPTS;
198
- this.lockoutDurationMs = options.lockoutDurationMs ?? exports.DEFAULT_LOCKOUT_DURATION_MS;
199
- this.resetTokenExpiryMs = options.resetTokenExpiryMs ?? exports.DEFAULT_RESET_TOKEN_EXPIRY_MS;
200
- this.minPasswordLength = options.minPasswordLength ?? exports.DEFAULT_MIN_PASSWORD_LENGTH;
201
- this.customPasswordValidator = options.validatePassword;
202
- if (sessionOrManager instanceof session_js_1.SessionManager) {
203
- this.sessionManager = sessionOrManager;
212
+ this.algorithm = resolvedOptions.algorithm || exports.DEFAULT_PASSWORD_ALGORITHM;
213
+ this.iterations = resolvedOptions.iterations || exports.DEFAULT_PASSWORD_ITERATIONS;
214
+ this.saltBytes = resolvedOptions.saltBytes || exports.DEFAULT_SALT_BYTES;
215
+ this.maxFailedAttempts = resolvedOptions.maxFailedAttempts ?? exports.DEFAULT_LOCKOUT_ATTEMPTS;
216
+ this.lockoutDurationMs = resolvedOptions.lockoutDurationMs ?? exports.DEFAULT_LOCKOUT_DURATION_MS;
217
+ this.resetTokenExpiryMs = resolvedOptions.resetTokenExpiryMs ?? exports.DEFAULT_RESET_TOKEN_EXPIRY_MS;
218
+ this.minPasswordLength = resolvedOptions.minPasswordLength ?? exports.DEFAULT_MIN_PASSWORD_LENGTH;
219
+ this.customPasswordValidator = resolvedOptions.validatePassword;
220
+ this.remoteAuthHandler = resolvedOptions.remoteAuthHandler;
221
+ if (resolvedSession instanceof session_js_1.SessionManager) {
222
+ this.sessionManager = resolvedSession;
204
223
  }
205
224
  else {
206
- this.sessionManager = new session_js_1.SessionManager(this.db, this.events, sessionOrManager);
225
+ this.sessionManager = new session_js_1.SessionManager(this.db, this.events, resolvedSession);
226
+ }
227
+ }
228
+ /**
229
+ * Registers a pluggable remote authentication exchange handler.
230
+ */
231
+ setRemoteAuthHandler(handler) {
232
+ this.remoteAuthHandler = handler;
233
+ }
234
+ /**
235
+ * Gets the configured remote authentication exchange handler.
236
+ */
237
+ getRemoteAuthHandler() {
238
+ return this.remoteAuthHandler;
239
+ }
240
+ /**
241
+ * Triggers token exchange with the registered remote sync provider for the active session.
242
+ */
243
+ async exchangeRemoteAuth() {
244
+ if (!this.remoteAuthHandler)
245
+ return null;
246
+ const session = await this.sessionManager.getActiveSession();
247
+ if (!session || !session.userId)
248
+ return null;
249
+ const user = await this.getUserById(session.userId);
250
+ if (!user)
251
+ return null;
252
+ const result = await this.remoteAuthHandler({ user, session });
253
+ if (result && result.token) {
254
+ await this.sessionManager.updateTokens({ token: result.token });
255
+ session.token = result.token;
207
256
  }
257
+ return result;
258
+ }
259
+ /**
260
+ * Retrieves the cached remote sync authentication token from the active session.
261
+ */
262
+ async getRemoteAuthToken() {
263
+ const session = await this.sessionManager.getActiveSession();
264
+ return session?.token || null;
208
265
  }
209
266
  /**
210
267
  * Retrieves the underlying SessionManager instance.
@@ -341,6 +398,18 @@ class LocalAuthEngine {
341
398
  offlineDurationMs: options.offlineDurationMs,
342
399
  setActive: true,
343
400
  });
401
+ if (this.remoteAuthHandler && session) {
402
+ try {
403
+ const remoteRes = await this.remoteAuthHandler({ user, session });
404
+ if (remoteRes && remoteRes.token) {
405
+ await this.sessionManager.updateTokens({ token: remoteRes.token });
406
+ session.token = remoteRes.token;
407
+ }
408
+ }
409
+ catch {
410
+ // Non-fatal if offline
411
+ }
412
+ }
344
413
  }
345
414
  this.events?.emit(this.usersTable, { operation: 'SIGN_UP', user });
346
415
  return { user, session };
@@ -426,6 +495,18 @@ class LocalAuthEngine {
426
495
  offlineDurationMs: options.offlineDurationMs,
427
496
  setActive: true,
428
497
  });
498
+ if (this.remoteAuthHandler && session) {
499
+ try {
500
+ const remoteRes = await this.remoteAuthHandler({ user, session });
501
+ if (remoteRes && remoteRes.token) {
502
+ await this.sessionManager.updateTokens({ token: remoteRes.token });
503
+ session.token = remoteRes.token;
504
+ }
505
+ }
506
+ catch {
507
+ // Non-fatal if offline
508
+ }
509
+ }
429
510
  }
430
511
  this.events?.emit(this.usersTable, { operation: 'SIGN_IN', user, session });
431
512
  return { user, session };
@@ -1,5 +1,5 @@
1
1
  import { LocalDBAdapter, LocalTransaction } from '../adapters/local/index.js';
2
- import { RemoteDBAdapter } from '../adapters/remote/index.js';
2
+ import { RemoteAutomationJob, RemoteBackupArchive, RemoteDBAdapter } from '../adapters/remote/index.js';
3
3
  import { EventEmitter } from '../reactive/event-emitter.js';
4
4
  import { SyncWorker } from './sync-worker.js';
5
5
  import { type OutboxDeleteClause } from './outbox-store.js';
@@ -132,6 +132,30 @@ export declare class LocalFirstClient {
132
132
  private initialization?;
133
133
  constructor(config: LocalFirstClientConfig);
134
134
  getPrimaryKey(): string;
135
+ /**
136
+ * Invokes a remote function, action, or RPC through the configured remote backend adapter.
137
+ * Works seamlessly across Convex actions/mutations, Supabase Edge Functions/RPC, etc.
138
+ */
139
+ call<T = any>(functionName: string, args?: any): Promise<T>;
140
+ /**
141
+ * Executes a remote query through the configured remote backend adapter.
142
+ */
143
+ queryRemote<T = any>(queryName: string, args?: any): Promise<T>;
144
+ /**
145
+ * Cloud automation / scheduled cron job controls.
146
+ */
147
+ get automations(): {
148
+ list: () => Promise<RemoteAutomationJob[]>;
149
+ setEnabled: (jobId: string, enabled: boolean) => Promise<void>;
150
+ };
151
+ /**
152
+ * Lists remote database backup archives from cloud storage.
153
+ */
154
+ listBackups(): Promise<RemoteBackupArchive[]>;
155
+ /**
156
+ * Retrieves a download URL for a file stored in the remote backend.
157
+ */
158
+ getDownloadUrl(fileIdOrKey: string): Promise<string | null>;
135
159
  /**
136
160
  * Options for TableManager.applyMutation on locally-originated writes.
137
161
  * The touch value uses the mutation timestamp so it matches what remote