All files / app/services powersync.ts

100% Statements 148/148
70.88% Branches 56/79
100% Functions 26/26
100% Lines 135/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343                          1x               1x                         1x                 1x                 1x                   1x                         1x                 1x                   3x     3x 3x 3x   3x   3x   3x 3x 3x 3x 3x       2x 2x               2x                     2x 2x     2x       3x 3x 3x 3x 3x 3x 3x   3x   3x   3x       3x 3x       3x 3x       3x 3x       3x   3x 3x         3x             3x       2x 2x 2x 2x 2x   2x       3x 3x 3x 3x   3x       3x 3x 3x 3x   3x       3x 3x 3x 3x       3x         3x 3x 3x 3x   3x   3x 3x 3x 3x     3x 3x 3x 3x     3x 3x 3x   3x 3x         3x 3x 3x 3x       3x   3x             3x 3x 3x     3x 3x   3x   3x 3x 3x 3x 3x 3x 3x   3x     3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x       3x 3x 3x   3x 3x   3x 3x   3x 3x 3x     3x 3x 3x      
import { Injectable, signal } from '@angular/core';
import { AbstractPowerSyncDatabase, Column, column, createBaseLogger, LogLevel, PowerSyncDatabase, Query, QueryResult, Schema, SyncStream, SyncStreamSubscription, Table, WASQLiteOpenFactory, WASQLiteVFS } from '@powersync/web';
import { SupabaseConnector } from './supabase-connector';
import { BehaviorSubject, filter, firstValueFrom, take } from 'rxjs';
import { Session } from '@supabase/supabase-js';
 
export const LISTS_TABLE = 'Lists';
export const CATEGORY_TABLE = 'Category';
export const ITEM_TABLE = 'Item';
export const FAVORITES_TABLE = 'Favorites';
export const USER_LISTS_TABLE = 'UserLists';
export const LIST_ITEMS_TABLE = 'ListItem';
 
const Category = new Table(
  {
    created_at: column.text,
    name: column.text
  },
  { indexes: { cid_idx: ["id"]} }
);
 
const Item = new Table(
  {
    created_at: column.text,
    name: column.text,
    category: column.integer,
    content: column.integer,
    description: column.text,
    global: column.integer,
    user: column.text
  },
  { indexes: { iid_idx: ["id"] } }
);
 
const Favorites = new Table(
  {
    created_at: column.text,
    user: column.text,
    item: column.integer
  },
  { indexes: { fid_idx: ["id"] } }
);
 
const UserLists = new Table(
  {
    created_at: column.text,
    user: column.text,
    list: column.integer
  },
  { indexes: { user_list_idx: ["user", "list"] } }
);
 
const Lists = new Table(
  {
    created_at: column.text,
    name: column.text,
    description: column.text
  },
  { indexes: { lists_idx: ["id"] } }
 
);
 
const ListItem = new Table(
  {
    liste: column.integer,
    item: column.integer,
    created_at: column.text,
    updated_at: column.text,
    curr_amount: column.integer,
    target_amount: column.integer,
    amount_unit: column.text
  },
  { indexes: { liste_item_idx: ["liste", "item"] } }
);
 
export const publicSchema = new Schema({
  Category,
  Item,
  Favorites,
  UserLists,
  Lists,
  ListItem
});
 
export const USER_ID_PLACEHOLDER = '__USER_ID__';
export interface USER_LIST_ID_PLACEHOLDER {
  user: string, 
  list: bigint
};
 
 
@Injectable({
  providedIn: 'root'
})
export class PowerSyncService {
  db: AbstractPowerSyncDatabase;
  currentUserId!: string;
  private isReady$ = new BehaviorSubject<boolean>(false);
  public ready$ = this.isReady$.asObservable();
  public readonly error = signal<boolean>(false);
 
  private authWatcherEnabled = false;
 
  private readonly isCypressRun = typeof window !== 'undefined' && !!(window as any).Cypress;
 
  private dbConnected = false;
  private subscribed = false;
  private syncStreamNames = ['watch_lists', 'watch_categories', "watch_items"];
  private syncStreams: SyncStreamSubscription[] = []
  private connector: SupabaseConnector | null = null;
 
 
  constructor() {
    const cypressFlags = this.isCypressRun ? { enableMultiTabs: false } : undefined;
    const factory = new WASQLiteOpenFactory({
      dbFilename: 'app_v6.db',
      vfs: this.isCypressRun ? WASQLiteVFS.IDBBatchAtomicVFS : WASQLiteVFS.OPFSCoopSyncVFS,
      ...(cypressFlags ? { flags: cypressFlags } : {}),
      // Specify the path to the worker script
      worker: '@powersync/worker/WASQLiteDB.umd.js'
    });
 
    this.db = new PowerSyncDatabase({
      schema: publicSchema,
      database: factory,
      ...(cypressFlags ? { flags: cypressFlags } : {}),
 
      sync: {
        // Specify the path to the worker script
        worker: '@powersync/worker/SharedSyncImplementation.umd.js'
      }
    });
 
    Eif (typeof window !== 'undefined') {
        (window as any).powerSync = this.db;
    }
 
    this.currentUserId = this.getOrCreateUserId();
  }
 
  execute(sql: string, parameters: unknown[] = []): Promise<QueryResult> {
    const injectedParameters = parameters.map(param => {
      if (param === USER_ID_PLACEHOLDER) {
        return this.currentUserId;
      E} else if (typeof param === 'object' && param !== null && 'user' in param && 'list' in param) {
        const placeholder = param as USER_LIST_ID_PLACEHOLDER;
        Eif (placeholder.user === USER_ID_PLACEHOLDER) {
          return `${this.currentUserId}|${placeholder.list}`;
        } 
        return `${placeholder.user}|${placeholder.list}`;
      } 
      return param;
    });
    return this.db.execute(sql, injectedParameters);
  }
 
  get<T>(sql: string, parameters: unknown[] = []): Promise<T> {
    const injectedParameters = parameters.map(param => param === USER_ID_PLACEHOLDER ? this.currentUserId : param);
    return this.db.get<T>(sql, injectedParameters);
  }
 
  watch(sql: string, parameters: unknown[] = []): AsyncIterable<QueryResult> {
    const injectedParameters = parameters.map(param => param === USER_ID_PLACEHOLDER ? this.currentUserId : param);
    return this.db.watch(sql, injectedParameters);
  }
 
  query<T>(sql: string, parameters: unknown[] = []): Query<T> {
    const injectedParameters: string[] = parameters.map(param => param === USER_ID_PLACEHOLDER ? this.currentUserId : String(param));
    return this.db.query<T>({sql, parameters: injectedParameters});
  }
 
  watchWithCallback(sql: string, callback: (result: QueryResult) => void, parameters: unknown[] = []) {
    const injectedParameters = parameters.map(param => param === USER_ID_PLACEHOLDER ? this.currentUserId : param);
 
    const controller = new AbortController();
    this.db.watchWithCallback(
      sql,
      injectedParameters,
      {
        onResult: callback,
        onError: (error) => console.error('Watch error:', error)
      },
      {
        signal: controller.signal
      }
    );
 
    return () => controller.abort();
  }
 
  getOrCreateUserId(): string {
    const localStorageKey = 'nimmit_user_id';
    let userId = localStorage.getItem(localStorageKey);
    Eif (!userId) {
      userId = crypto.randomUUID();
      localStorage.setItem(localStorageKey, userId);
    }
    return userId;
  }
 
  async subscibeAllSyncStreams() {
    Eif (this.subscribed) return;
    for (const streamName of this.syncStreamNames) {
      const sub = await this.db.syncStream(streamName).subscribe();
      this.syncStreams.push(sub);
    }
    this.subscribed = true;
  }
 
  async unsubscribeAllSyncStreams() {
    Eif (!this.subscribed) return;
    for (const sub of this.syncStreams) {
      sub.unsubscribe();
      this.syncStreams = this.syncStreams.filter(s => s !== sub);
    }
    this.subscribed = false;
  }
 
  async migrateUserIid(oldId: string, newId: string) {
    const criticalTables = ["Item", "Favorites", "UserLists"];
    for (const table of criticalTables) {
      const updateColumn = "user";
      const sql = `
        UPDATE ${table} set ${updateColumn} = ?
        Where ${updateColumn} = ?
      `;
      await this.db.execute(sql, [newId, oldId]);
    }
  }
 
  async connectDb(session: Session | null) {
    Eif (this.dbConnected) return;
    Eif (!this.connector) {
      console.warn('Attempted to connect Supabase database without a connector - aborting connection.');
      return;
    }
    Eif (!session) {
      // eslint-disable-next-line no-param-reassign
      session = await this.connector.getSession();
      Eif (!session) {
        console.warn('No active session found for PowerSync database connection - aborting connection.');
        return;
      }
    }
    Eif (this.currentUserId !== session.user.id) {
      const previousUserId = this.currentUserId;
      await this.migrateUserIid(previousUserId, session.user.id);
      this.currentUserId = session.user.id;
    }
 
    await this.db.connect(this.connector);
    await this.subscibeAllSyncStreams();
    this.dbConnected = true;
 
    void this.db.waitForFirstSync().catch((error) => {
      console.error('PowerSync first sync failed:', error);
    });
  }
 
  async disconnectDb() {
    Eif (!this.dbConnected) return;
    await this.db.disconnect();
    await this.unsubscribeAllSyncStreams();
    this.dbConnected = false;
  }
 
  async waitForPowerSyncReady(): Promise<void> {
    await firstValueFrom(
      this.ready$.pipe(
        filter((isReady) => isReady),
        take(1)
      )
    );
  }
 
  toggleSignInWatcher() {
    Eif (!this.connector) {
      console.warn('Attempted to toggle PowerSync database connection without a connector - aborting.');
      return;
    }
 
    Eif (this.authWatcherEnabled) {
      return;
    }
    this.authWatcherEnabled = true;
 
    this.connector.client.auth.onAuthStateChange(async (event, session) => {
      if (event === "SIGNED_IN") {
        Eif (!this.dbConnected) {
          if (session) {
            this.isReady$.next(false);
            await this.connectDb(session);
            this.isReady$.next(true);
          } else {            
            console.warn('Received SIGNED_IN event without a session - cannot connect to database.');
          }
        }
      E} else if (event === "SIGNED_OUT") {
        this.isReady$.next(false);
        await this.disconnectDb();
        this.currentUserId = this.getOrCreateUserId();
        this.isReady$.next(true);
      }
    });
  }
 
  setupPowerSync = async (connector: SupabaseConnector | null) => {
    try {
      await this.db.init();
      if (connector) {
        this.connector = connector;
        this.toggleSignInWatcher();
        const session = await connector.getSession();
        Eif (!session) {
          console.warn('No active session found for PowerSync setup - database will operate in offline mode only with local user ID: ', this.currentUserId);
          this.isReady$.next(true);
          return;
        }
        this.currentUserId = session.user.id;
 
        // Cypress E2E runs use a mocked Supabase session. Avoid connecting to the real
        // PowerSync backend, as it would require a valid access token and can hang/flap in CI.
        Eif (this.isCypressRun) {
          this.isReady$.next(true);
          return;
        }
        Eif (navigator.onLine) {
          await this.connectDb(session);
        }
        console.log('PowerSync setup complete with user ID:', this.currentUserId);
        this.isReady$.next(true);
      } else {
        console.warn('PowerSync setup called without a connector - database will operate in offline mode only with local user ID: ', this.currentUserId);
        this.toggleSignInWatcher();
        this.isReady$.next(true);
      }
    } catch (e) {
      console.error('Error during PowerSync setup:', e); 
      this.isReady$.next(true); 
      this.error.set(true);
    }
  };
}