All files gulp.safelink.ts

15.9% Statements 21/132
100% Branches 0/0
0% Functions 0/1
15.9% Lines 21/132

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 1331x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                               1x 1x 1x  
import ansiColors from 'ansi-colors';
import { existsSync } from 'fs';
import gulp from 'gulp';
import path from 'path';
import sf, { SafelinkOptions } from 'safelinkify';
import through2 from 'through2';
import { SrcOptions } from 'vinyl-fs';
import gulpCached from './gulp-utils/gulp.cache';
import { createWriteStream } from './utils/fm';
import Logger from './utils/logger';
import { getConfig } from './_config';
 
/**
 * Process Safelink on Deploy Dir
 * @param _done callback function
 * @param cwd working directory to scan html's
 * @returns
 */
export function taskSafelink(_done?: gulp.TaskFunctionCallback | null | undefined, cwd?: undefined | null | string) {
  const config = getConfig();
  const workingDir = typeof cwd === 'string' ? cwd : config.deploy.deployDir;
  const logname = ansiColors.greenBright('safelink');

  // skip process safelink
  let hasError = false;
  if (!config.external_link.safelink) {
    hasError = true;
    Logger.log(logname, 'config safelink', ansiColors.red('not configured'));
  }
  if (!config.external_link.safelink.redirect) {
    hasError = true;
    Logger.log(logname, 'safelink redirector', ansiColors.red('not configured'));
  }
  if (!config.external_link.safelink.enable) {
    hasError = true;
    Logger.log(logname, ansiColors.red('disabled'));
  }

  if (existsSync(workingDir) && !hasError) {
    const defaultConfigSafelink: SafelinkOptions & Record<string, any> = {
      enable: false,
      exclude: [] as string[],
      redirect: 'https://www.webmanajemen.com/page/safelink.html?url=',
      password: 'root',
      type: 'base64'
    };
    const configSafelink = Object.assign(defaultConfigSafelink, config.external_link.safelink || {});
    let baseURL = '';
    try {
      baseURL = new URL(config.url).host;
    } catch {
      //
    }

    const opt: Partial<SafelinkOptions> = {
      // exclude patterns (dont anonymize these patterns)
      exclude: [
        ...(config.external_link?.exclude || []),
        /https?:\/\/?(?:([^*]+)\.)?webmanajemen\.com/,
        /([a-z0-9](?:[a-z0-9-]{1,61}[a-z0-9])?[.])*webmanajemen\.com/,
        baseURL,
        'www.webmanajemen.com',
        'https://github.com/dimaslanjaka',
        'https://facebook.com/dimaslanjaka1',
        'dimaslanjaka.github.io',
        ...configSafelink.exclude
      ].filter(function (x, i, a) {
        // remove duplicate and empties
        return a.indexOf(x) === i && x.toString().trim().length !== 0;
      }),
      redirect: [],
      //redirect: [, configSafelink.redirect],
      password: configSafelink.password || config.external_link.safelink.password,
      type: configSafelink.type || config.external_link.safelink.type
    };

    if (configSafelink.redirect) {
      opt.redirect = configSafelink.redirect;
    }

    const safelink = new sf.safelink(opt);

    const gulpopt: SrcOptions = {
      cwd: workingDir,
      ignore: []
    };

    if (Array.isArray(config.external_link.exclude)) {
      gulpopt.ignore?.concat(...config.external_link.exclude);
    }
    if (Array.isArray(configSafelink.exclude)) {
      const ignore = configSafelink.exclude.filter((str) => {
        if (typeof str === 'string') {
          return !/^(https?:\/|www.)/.test(str);
        }
        return false;
      }) as string[];
      gulpopt.ignore?.concat(...ignore);
    }

    return gulp
      .src(['**/*.{html,htm}'], gulpopt)
      .pipe(gulpCached({ name: 'safelink' }))
      .pipe(
        through2.obj(async (file, _enc, next) => {
          // drops
          if (file.isNull() || file.isDirectory() || !file || file.isStream()) return next();
          // process
          if (file.isBuffer() && Buffer.isBuffer(file.contents)) {
            // do safelinkify
            const content = file.contents.toString('utf-8');
            const parsed = await safelink.parse(content);
            if (typeof parsed === 'string') {
              // Logger.log(parsed);
              file.contents = Buffer.from(parsed);
              return next(null, file);
            }
          }
          Logger.log('cannot parse', file.path);
          // drop fails
          next();
        })
      )
      .pipe(gulp.dest(workingDir));
  } else {
    const wstream = createWriteStream(path.join(config.cwd, 'tmp/errors/safelink.log'));
    return wstream;
  }
}
 
// safelinkify the deploy folder
gulp.task('safelink', taskSafelink);