/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');
const moduleHook = require('../../../hooks/require');
const { propagate } = require('./common');
const { isString } = require('../../../util/is-string');

const NAMESPACE_PREFIX = '\\\\?\\';
const UNC_STR = 'UNC\\';

module.exports.handle = function handle() {
  moduleHook.resolve({ name: 'path' }, (path) => {
    patcher.patch(path.win32, 'toNamespacedPath', {
      name: 'path.win32.toNamespacedPath',
      patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
      post(data) {
        const { result } = data;
        // If the result doesn't start with \\? then no namespace was prepended.
        if (!result || !isString(result) || !result.startsWith(NAMESPACE_PREFIX)) return;
        const resultMeta = {
          evaluator: (segmentOffset) => segmentOffset > -1,
          method: 'path.toNamespacedPath',
          offset: NAMESPACE_PREFIX.length,
          parents: [],
          str: result,
          tagRanges: []
        };

        if (result.startsWith(`${NAMESPACE_PREFIX}${UNC_STR}`)) {
          // add 4 for UNC\, subtract 2 for .slice(2) that occurs inside toNamespacePath
          resultMeta.offset += UNC_STR.length - 2;
        }

        propagate({ resultMeta, data, win32: true });
      }
    });
  });
};
