All files / lib Client.ts

100% Statements 99/99
97.96% Branches 48/49
100% Functions 20/20
100% Lines 74/74

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 2161x 1x 1x                                                                                             1x 21x                   21x 21x     21x 21x 21x 21x 21x   20x     1x 18x 5x 1x             1x 21x 1x   1x 1x     1x             19x 19x 4x 1x     4x             1x 19x       19x           18x     1x 21x 19x   38x   18x   18x 18x     37x 2x     19x     40x 40x       22x 16x 5x 1x     18x                   18x 18x 2x   16x     16x       31x 1x     30x   15x     1x 19x 19x   18x 18x     36x 20x 17x 17x 17x 17x               17x   17x 1x     16x   1x  
import buildUrl from 'build-url';
import { ComponentGetFailedError } from './errors';
import { StorageController } from './utils/StorageController';
 
export type Dependencies = Record<string, string>;
 
export interface Mismatches {
  [dependency: string]: {
    host: string;
    component: string;
  };
}
 
export type Issues = {
  [component: string]: {
    mismatches: Mismatches;
    version: string;
  };
};
 
export interface InitOptions {
  prefix?: string;
  url: string;
  cache: Storage;
  dependencies: {
    versions: Dependencies;
    resolvers: Record<string, any>;
  };
  fetcher?: GlobalFetch['fetch'];
  globals?: Record<string, any>;
}
 
export interface Options {
  componentVersion?: string;
  ignoreCache?: boolean;
  globals?: Record<string, any>;
}
 
interface RegisterHostResponse {
  id: string;
  issues: Issues;
}
 
const enum ReadyState {
  NotInitialized,
  Initializing,
  Ready
}
 
export class DynamicoClient {
  id: string = '';
  url: string;
  dependencies: {
    versions: Dependencies;
    resolvers: Record<string, any>;
  };
  cache: StorageController;
  fetcher: GlobalFetch['fetch'];
  globals: Record<string, any>;
 
  private readyState: ReadyState = ReadyState.NotInitialized;
  private requestQueue: Function[] = [];
 
  constructor(options: InitOptions) {
    this.url = options.url;
    this.cache = new StorageController(options.prefix || '@dynamico', options.cache);
    this.dependencies = options.dependencies;
    this.globals = options.globals || {};
    this.checkFetcher(options.fetcher);
 
    this.fetcher = options.fetcher || fetch.bind(window);
  }
 
  private handleIssues(issues: Issues): void {
    Object.entries(issues).forEach(([comp, { version, mismatches }]) =>
      Object.entries(mismatches).forEach(([dependency, { host, component }]) =>
        console.warn(
          `${comp}@${version} requires ${dependency}@${component} but host provides ${host}. Please consider upgrade to version ${component}`
        )
      )
    );
  }
 
  private checkFetcher(fetcher?: GlobalFetch['fetch']) {
    if (!fetcher && typeof fetch === 'undefined') {
      let library: string = 'unfetch';
 
      Eif (typeof window === 'undefined') {
        library = 'node-fetch';
      }
 
      throw new Error(`
        fetch is not found globally and no fetcher passed, to fix pass a fetch for 
        your environment like https://www.npmjs.com/package/${library}.
      `);
    }
  }
 
  private filterMissingDependencies({ versions, resolvers }: DynamicoClient['dependencies']): Dependencies {
    return Object.keys(resolvers).reduce((sum, name) => {
      if (!versions[name]) {
        console.warn(`Missing version specifier for ${name}`);
      }
 
      return {
        ...sum,
        ...(versions[name] ? { [name]: versions[name] } : undefined)
      };
    }, {});
  }
 
  private async register(dependencies: Dependencies) {
    const url = buildUrl(this.url, {
      path: '/host/register'
    });
 
    return await this.fetcher(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(dependencies)
    }).then((res: Response) => res.json());
  }
 
  private async isReady() {
    if (this.readyState === ReadyState.NotInitialized) {
      this.readyState = ReadyState.Initializing;
 
      await this.initialize();
 
      this.readyState = ReadyState.Ready;
 
      this.requestQueue.forEach(handler => handler());
      this.requestQueue = [];
    }
 
    if (this.readyState !== ReadyState.Ready) {
      await new Promise(resolve => this.requestQueue.push(() => resolve()));
    }
 
    return true;
  }
 
  private async fetchJs(name: string, { ignoreCache, componentVersion = undefined }: Options): Promise<string> {
    await this.isReady();
 
    let latestComponentVersion: string | undefined;
 
    if (!componentVersion) {
      latestComponentVersion = this.cache.getLatestVersion(name);
    } else if (!ignoreCache && this.cache.has(name, componentVersion)) {
      return (await this.cache.getItem(name, componentVersion)) as string;
    }
 
    const url = buildUrl(this.url, {
      path: name,
      queryParams: {
        hostId: this.id,
        ...(componentVersion
          ? { componentVersion }
          : latestComponentVersion && !ignoreCache && { latestComponentVersion })
      }
    });
 
    const { statusCode, version, code } = await this.fetcher(url).then(async (res: Response) => {
      if (!res.ok) {
        throw new ComponentGetFailedError(res.statusText, res);
      }
      return {
        statusCode: res.status,
        version: res.headers.get('dynamico-component-version') as string,
        code: await res.text()
      };
    });
 
    if (statusCode === 204) {
      return (await this.cache.getItem(name, version)) as string;
    }
 
    await this.cache.setItem(name, version, code);
 
    return code;
  }
 
  private async initialize() {
    const versions = this.filterMissingDependencies(this.dependencies);
    const { id, issues }: RegisterHostResponse = await this.register(versions);
 
    this.id = id;
    this.handleIssues(issues);
  }
 
  async get(name: string, options: Options = {}) {
    const code = await this.fetchJs(name, options);
    const require = (dep: string) => this.dependencies.resolvers[dep];
    const module: any = {};
    const exports: any = {};
    const args = {
      module,
      exports,
      require,
      ...this.globals,
      ...options.globals
    };
 
    new Function(...Object.keys(args), code)(...Object.values(args));
 
    if (module.exports) {
      return module.exports;
    }
 
    return exports.default;
  }
}