All files / src fragment.ts

89.83% Statements 159/177
81.15% Branches 99/122
90.32% Functions 28/31
90.12% Lines 155/172
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 4658x                   8x 8x 8x 8x 8x 8x   8x     8x   8x 8x     8x 8x   8x       120x       8x     36x     36x 36x   36x 1x     36x                   25x 25x 25x 24x   23x 23x             23x 21x 21x 21x         2x     1x     1x                     4x 4x 4x 3x   1x                                                   25x 25x 16x 16x 16x   25x 16x   25x                             36x 43x 43x 42x   1x             8x   84x 84x                   84x   84x                     65x 1x   65x   65x 65x 60x     65x   65x   65x 3x     65x 11x           137x   118x 118x   118x       118x 2x 2x     116x               8x   8x 1x 1x     7x 1x 1x     6x         5x   5x 5x     1x 1x                   16x   16x         16x 2x     14x         3x   3x 3x     11x 11x                                 8x 37x 37x 1x 1x                 36x           36x       36x 22x 8x 8x         22x 8x 8x 8x       36x           36x 36x 36x 36x 36x   36x   36x         34x 34x             2x 2x   2x   2x                                 3x   3x 1x 1x     2x   2x       2x   2x 1x 1x     1x     1x       1x 1x 1x   1x       1x                           4x 1x 1x     3x   3x 1x 1x     2x        
import fetch from "node-fetch";
import {
    HandlerDataResponse, ICookieMap,
    IExposeFragment,
    IFileResourceAsset,
    IFragment,
    IFragmentBFF,
    IFragmentContentResponse,
    IFragmentHandler
} from "./types";
import {CONTENT_ENCODING_TYPES, FRAGMENT_RENDER_MODES} from "./enums";
import * as querystring from "querystring";
import {DEBUG_QUERY_NAME, DEFAULT_CONTENT_TIMEOUT, PREVIEW_PARTIAL_QUERY_NAME, RENDER_MODE_QUERY_NAME} from "./config";
import url from "url";
import path from "path";
import {container, TYPES} from "./base";
import {Logger} from "./logger";
import {decompress} from "iltorb";
import {Request} from 'express';
import {HttpClient} from "./client";
import {ERROR_CODES, PuzzleError} from "./errors";
import express from "express";
import {CookieVersionMatcher} from "./cookie-version-matcher";
import {nrSegmentAsync} from "./decorators";
 
 
const logger = container.get(TYPES.Logger) as Logger;
const httpClient = container.get(TYPES.Client) as HttpClient;
 
export class Fragment {
    name: string;
 
    constructor(config: IFragment) {
        this.name = config.name;
    }
}
 
export class FragmentBFF extends Fragment {
    config: IFragmentBFF;
    versionMatcher?: CookieVersionMatcher;
    private handler: { [version: string]: IFragmentHandler } = {};
 
    constructor(config: IFragmentBFF) {
        super({name: config.name});
        this.config = config;
 
        if (this.config.versionMatcher) {
            this.versionMatcher = new CookieVersionMatcher(this.config.versionMatcher);
        }
 
        this.prepareHandlers();
    }
 
    /**
     * Renders fragment: data -> content
     * @param {object} req
     * @param {string} version
     * @returns {Promise<HandlerDataResponse>}
     */
    async render(req: express.Request, version: string): Promise<HandlerDataResponse> {
        const handler = this.handler[version] || this.handler[this.config.version];
        const clearedRequest = this.clearRequest(req);
        if (handler) {
            if (handler.data) {
                let dataResponse;
                try {
                    dataResponse = await handler.data(clearedRequest);
                } catch (e) {
                    logger.error(`Failed to fetch data for fragment ${this.config.name}`, req.url, req.query, req.params, req.headers, e);
                    return {
                        $status: 500
                    };
                }
                if (dataResponse.data) {
                    const renderedPartials = handler.content(clearedRequest, dataResponse.data);
                    delete dataResponse.data;
                    return {
                        ...renderedPartials,
                        ...dataResponse
                    };
                } else {
                    return dataResponse;
                }
            } else {
                throw new Error(`Failed to find data handler for fragment. Fragment: ${this.config.name}, Version: ${version || this.config.version}`);
            }
        } else {
            throw new Error(`Failed to find fragment version. Fragment: ${this.config.name}, Version: ${version || this.config.version}`);
        }
    }
 
    /**
     * Renders placeholder
     * @param {object} req
     * @param {string} version
     * @returns {string}
     */
    placeholder(req: object, version?: string) {
        const fragmentVersion = (version && this.config.versions[version]) ? version : this.config.version;
        const handler = this.handler[fragmentVersion];
        if (handler) {
            return handler.placeholder();
        } else {
            throw new Error(`Failed to find fragment version. Fragment: ${this.config.name}, Version: ${version || this.config.version}`);
        }
    }
 
    /**
     * Renders error
     * @param {object} req
     * @param {string} version
     * @returns {string}
     */
    errorPage(req: object, version?: string) {
        const fragmentVersion = (version && this.config.versions[version]) ? version : this.config.version;
        const handler = this.handler[fragmentVersion];
        if (handler) {
            return handler.error();
        } else {
            throw new Error(`Failed to find fragment version. Fragment: ${this.config.name}, Version: ${version || this.config.version}`);
        }
    }
 
    /**
     * Purifies req.path, req.query from Puzzle elements.
     * @param req
     * @returns {*}
     */
    private clearRequest(req: express.Request) {
        const clearedReq = Object.assign({}, req);
        if (req.query) {
            delete clearedReq.query[RENDER_MODE_QUERY_NAME];
            delete clearedReq.query[PREVIEW_PARTIAL_QUERY_NAME];
            delete clearedReq.query[DEBUG_QUERY_NAME];
        }
        if (req.path) {
            clearedReq.path = req.path.replace(`/${this.name}`, '');
        }
        return clearedReq;
    }
 
    /**
     * Check module type
     */
    private checkModuleType(fragmentModule: IFragmentHandler | Function): IFragmentHandler {
        if (typeof fragmentModule === "function") return fragmentModule(container);
        return fragmentModule;
    }
 
    /**
     * Resolve handlers based on configuration
     */
    private prepareHandlers() {
        Object.keys(this.config.versions).forEach(version => {
            const configurationHandler = this.config.versions[version].handler;
            if (configurationHandler) {
                this.handler[version] = configurationHandler;
            } else {
                const module = require(path.join(process.cwd(), `/src/fragments/`, this.config.name, version));
                this.handler[version] = this.checkModuleType(module);
            }
        });
    }
}
 
export class FragmentStorefront extends Fragment {
    config: IExposeFragment | undefined;
    primary = false;
    shouldWait = false;
    from: string;
    gatewayPath!: string;
    fragmentUrl: string | undefined;
    assetUrl: string | undefined;
    private versionMatcher?: CookieVersionMatcher;
    private cachedErrorPage: string | undefined;
    private gatewayName: string;
 
    constructor(name: string, from: string) {
        super({name});
 
        this.from = from;
    }
 
    /**
     * Updates fragment configuration
     * @param {IExposeFragment} config
     * @param {string} gatewayUrl
     * @param gatewayName
     * @param {string | undefined} assetUrl
     */
    update(config: IExposeFragment, gatewayUrl: string, gatewayName: string, assetUrl?: string | undefined) {
        if (assetUrl) {
            this.assetUrl = url.resolve(assetUrl, this.name);
        }
        this.fragmentUrl = url.resolve(gatewayUrl, this.name);
 
        const hostname = url.parse(gatewayUrl).hostname;
        if (hostname) {
            this.gatewayPath = hostname;
        }
 
        this.gatewayName = gatewayName;
 
        this.config = config;
 
        if (this.config && this.config.versionMatcher) {
            this.versionMatcher = new CookieVersionMatcher(this.config.versionMatcher);
        }
 
        if (this.config && this.config.render.error && !this.cachedErrorPage) {
            this.getErrorPage();
        }
 
    }
 
    detectVersion(cookie: ICookieMap, preCompile = false): string {
        if (!this.config) return '0';
 
        const cookieKey = this.config.testCookie;
        const cookieVersion = cookie[cookieKey];
 
        Iif (cookieVersion) {
            return cookieVersion;
        }
 
        if (!preCompile && this.versionMatcher) {
            const version = this.versionMatcher.match(cookie);
            Eif (version) return version;
        }
 
        return this.config.version;
    }
 
    /**
     * Returns fragment placeholder as promise, fetches from gateway
     * @returns {Promise<string>}
     */
    async getPlaceholder(): Promise<string> {
        logger.info(`Trying to get placeholder of fragment: ${this.name}`);
 
        if (!this.config) {
            logger.error(new Error(`No config provided for fragment: ${this.name}`));
            return '';
        }
 
        if (!this.config.render.placeholder) {
            logger.error(new Error('Placeholder is not enabled for fragment'));
            return '';
        }
 
        return fetch(`${this.fragmentUrl}/placeholder`, {
            headers: {
                gateway: this.gatewayName
            }
        })
            .then(res => res.text())
            .then(html => {
                logger.info(`Received placeholder contents of fragment: ${this.name}`);
                return html;
            })
            .catch(err => {
                logger.error(`Failed to fetch placeholder for fragment: ${this.fragmentUrl}/placeholder`, err);
                return '';
            });
    }
 
 
    /**
     * Returns fragment error as promise, fetches from gateway
     * @returns { Promise<string> }
     */
    async getErrorPage(): Promise<string> {
        logger.info(`Trying to get error page of fragment: ${this.name}`);
 
        Iif (!this.config || !this.config.render.error) {
            logger.warn(new Error('Error is not enabled for fragment'));
            return '';
        }
 
        if (this.cachedErrorPage) {
            return this.cachedErrorPage;
        }
 
        return fetch(`${this.fragmentUrl}/error`, {
            headers: {
                gateway: this.gatewayName
            }
        })
            .then(res => res.json())
            .then(html => {
                this.cachedErrorPage = html;
                return html;
            })
            .catch(err => {
                logger.error(`Failed to fetch error for fragment: ${this.fragmentUrl}/error`, err);
                return '';
            });
    }
 
    /**
     * Fetches fragment content as promise, fetches from gateway
     * Returns {
     *  html: {
     *    Partials
     *  },
     *  status: gateway status response code
     * }
     * @param attribs
     * @param req
     * @returns {Promise<IFragmentContentResponse>}
     */
    @nrSegmentAsync("fragment.getContent", true)
    async getContent(attribs: any = {}, req?: Request): Promise<IFragmentContentResponse> {
        logger.info(`Trying to get contents of fragment: ${this.name}`);
        if (!this.config) {
            logger.error(new Error(`No config provided for fragment: ${this.name}`));
            return {
                status: 500,
                html: {},
                headers: {},
                cookies: {},
                model: {}
            };
        }
 
        let query = {
            ...attribs,
            __renderMode: FRAGMENT_RENDER_MODES.STREAM
        };
 
        let parsedRequest;
        const requestConfiguration: any = {
            timeout: this.config.render.timeout || DEFAULT_CONTENT_TIMEOUT,
        };
 
        if (req) {
            if (req.url) {
                parsedRequest = url.parse(req.url) as { pathname: string };
                query = {
                    ...query,
                    ...req.query,
                };
            }
            if (req.headers) {
                requestConfiguration.headers = req.headers;
                requestConfiguration.headers['originalurl'] = req.url;
                requestConfiguration.headers['originalpath'] = req.path;
            }
        }
 
        requestConfiguration.headers = {
            ...requestConfiguration.headers,
            gateway: this.gatewayName
        } || {gateway: this.gatewayName};
 
 
        delete query.from;
        delete query.name;
        delete query.partial;
        delete query.primary;
        delete query.shouldwait;
 
        const routeRequest = req && parsedRequest ? `${parsedRequest.pathname.replace('/' + this.name, '')}?${querystring.stringify(query)}` : `/?${querystring.stringify(query)}`;
 
        return httpClient.get(`${this.fragmentUrl}${routeRequest}`, this.name, {
            json: true,
            gzip: true,
            ...requestConfiguration
        }).then(res => {
            logger.info(`Received fragment contents of ${this.name} with status code ${res.response.statusCode}`);
            return {
                status: res.data.$status || res.response.statusCode,
                headers: res.data.$headers || {},
                cookies: res.data.$cookies || {},
                html: res.data,
                model: res.data.$model || {}
            };
        }).catch(async (err) => {
            logger.error(new PuzzleError(ERROR_CODES.FAILED_TO_GET_FRAGMENT_CONTENT, this.name, `${this.fragmentUrl}${routeRequest}`), this.name, `${this.fragmentUrl}${routeRequest}`, `${this.fragmentUrl}${routeRequest}`, {json: true, ...requestConfiguration}, err);
 
            const errorPage = await this.getErrorPage();
 
            return {
                status: errorPage ? 200 : 500,
                html: errorPage ? errorPage : {},
                headers: {},
                cookies: {},
                model: {}
            };
        });
    }
 
    /**
     * Returns asset content
     * @param {string} name
     * @param targetVersion
     * @returns {Promise<string>}
     */
    async getAsset(name: string, targetVersion: string) {
        logger.info(`Trying to get asset: ${name}`);
 
        if (!this.config) {
            logger.error(new Error(`No config provided for fragment: ${this.name}`));
            return null;
        }
 
        let fragmentVersion: { assets: IFileResourceAsset[] } = this.config;
 
        Iif (targetVersion !== this.config.version && this.config.passiveVersions && this.config.passiveVersions[targetVersion]) {
            fragmentVersion = this.config.passiveVersions[targetVersion];
        }
 
        const asset = fragmentVersion.assets.find(asset => asset.name === name);
 
        if (!asset) {
            logger.error(new Error(`Asset not declared in fragments asset list: ${name}`));
            return null;
        }
 
        const link = (asset.link || `${this.fragmentUrl}/static/${asset.fileName}`) + `?__version=${targetVersion}`;
 
 
        return fetch(link, {
            headers: {
                gateway: this.gatewayName
            }
        }).then(async res => {
            logger.info(`Asset received: ${name}`);
            const encoding = res.headers.get('content-encoding');
 
            switch (encoding) {
                case CONTENT_ENCODING_TYPES.BROTLI:
                    return await decompress(await res.buffer());
                default:
                    return await res.text();
            }
        }).catch(e => {
            logger.error(new Error(`Failed to fetch asset from gateway: ${this.fragmentUrl}/static/${asset.fileName}`));
            return null;
        });
    }
 
    /**
     * Returns asset path
     * @param {string} name
     * @returns {string}
     */
    getAssetPath(name: string) {
        if (!this.config) {
            logger.error(new Error(`No config provided for fragment: ${this.name}`));
            return null;
        }
 
        const asset = this.config.assets.find(asset => asset.name === name);
 
        if (!asset) {
            logger.error(new Error(`Asset not declared in fragments asset list: ${name}`));
            return null;
        }
 
        return asset.link || `${this.assetUrl || this.fragmentUrl}/static/${asset.fileName}`;
    }
}