All files / state/src/store transfer.ts

100% Statements 36/36
90% Branches 9/10
100% Functions 4/4
100% Lines 36/36

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 371x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 2x 2x 2x 4x 2x 2x 2x 4x 2x 2x 2x 1x  
import { transferHandlers } from 'comlink';
import { Store } from './store';
 
/**
 * Custom addition to the {@link transferHandlers}, allowing values of type
 * {@link Store} to be transparently transferred between endpoints.
 */
transferHandlers.set('store', {
  canHandle: (value: unknown): value is Store.Type<Store> => {
    return (value as Function | undefined)?.prototype instanceof Store;
  },
  deserialize: (value: Record<string, string>) => {
    const store = class extends Store {};
 
    for (const key of Object.getOwnPropertyNames(value)) {
      Object.defineProperty(store.prototype, key, {
        // eslint-disable-next-line @typescript-eslint/no-implied-eval
        value: new Function(`return (async ${value[key]});`)()
      });
    }
 
    return store;
  },
  serialize: (value: Store.Type<Store>) => {
    const store = {} as Record<string, string>;
 
    for (const key of Object.getOwnPropertyNames(value.prototype)) {
      if (!Store.prototype[key as keyof Store]) {
        const method = value.prototype[key as keyof Store].toString();
        store[key] = method.replace(/^[^(]+/, 'function');
      }
    }
 
    return [store, []];
  }
});