All files / lib/internal/http httpPreferences.ts

43.75% Statements 28/64
17.5% Branches 7/40
13.33% Functions 2/15
45.9% Lines 28/61

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 216 217 218 219 220 221 222 223 224 225 226 2271x 1x         1x 1x 1x 1x               1x   1x                           1x     1x         1x                     1x                             1x   1x                       1x       108x 108x     1x     36x       36x           36x         36x 36x         36x         36x                   1x                                                                     1x                                                   1x                                                                          
import { pipe, SideEffect2 } from "@reactive-js/core/lib/functions";
import {
  concatWith,
  map,
  parseWith,
} from "@reactive-js/core/lib/internal/parserCombinators";
import { isSome, Option, none } from "@reactive-js/core/lib/option";
import { map as mapReadonlyArray } from "@reactive-js/core/lib/readonlyArray";
import { pToken, pParams, httpList } from "./httpGrammar";
import { HttpStandardHeader, getHeaderValue } from "./httpHeaders";
import {
  HttpPreferences,
  HttpHeaders,
  MediaType,
  MediaRange,
  HttpContentEncoding,
} from "./interfaces";
import { pMediaType, parseMediaTypeOrThrow } from "./mediaType";
 
const weightedParamComparator = (
  a: {
    readonly [key: string]: string;
  },
  b: {
    readonly [key: string]: string;
  },
) => {
  const qA = (Number.parseFloat(a["q"]) ?? 1) * 1000;
  const qB = (Number.parseFloat(b["q"]) ?? 1) * 1000;
 
  return qA - qB;
};
 
const mediaRangeCompare = (a: MediaType, b: MediaType): number =>
  weightedParamComparator(a.params, b.params);
 
const mediaTypeToMediaRange = ({ type, subtype }: MediaType): MediaRange => ({
  type,
  subtype,
});
 
const parseAccept = pipe(
  pMediaType,
  httpList,
  map(mediaTypes => {
    // Mutate to avoid allocations. Kinda evil.
    (mediaTypes as MediaType[]).sort(mediaRangeCompare);
    return pipe(mediaTypes, mapReadonlyArray(mediaTypeToMediaRange));
  }),
  parseWith,
);
 
const weightedTokenComparator = (
  [, a]: [
    string,
    {
      readonly [key: string]: string;
    },
  ],
  [, b]: [
    string,
    {
      readonly [key: string]: string;
    },
  ],
) => weightedParamComparator(a, b);
 
const weightedTokenToToken = ([token]: [string, unknown]) => token;
 
const parseWeightedToken = pipe(
  pToken,
  concatWith(pParams),
  httpList,
  map(values => {
    // Mutate to avoid allocations. Kinda evil.
    (values as any[]).sort(weightedTokenComparator);
    return pipe(values, mapReadonlyArray(weightedTokenToToken));
  }),
  parseWith,
);
 
const parseWeightedTokenHeader = (
  headers: HttpHeaders,
  header: HttpStandardHeader,
) => {
  const rawValue = getHeaderValue(headers, header);
  return isSome(rawValue) ? parseWeightedToken(rawValue) ?? [] : [];
};
 
export const parseHttpPreferencesFromHeaders = (
  headers: HttpHeaders,
): Option<HttpPreferences> => {
  const acceptedCharsets = parseWeightedTokenHeader(
    headers,
    HttpStandardHeader.AcceptCharset,
  );
  const acceptedEncodings = parseWeightedTokenHeader(
    headers,
    HttpStandardHeader.AcceptEncoding,
  ) as readonly HttpContentEncoding[];
 
  // FIXME: This is overly lax. See: https://tools.ietf.org/html/draft-ietf-httpbis-semantics-07#section-8.4.5
  const acceptedLanguages = parseWeightedTokenHeader(
    headers,
    HttpStandardHeader.AcceptLanguage,
  );
 
  const rawAccept = getHeaderValue(headers, HttpStandardHeader.Accept);
  const acceptedMediaRanges = isSome(rawAccept)
    ? parseAccept(rawAccept) ?? []
    : [];
 
  const isUndefined =
    acceptedCharsets.length === 0 &&
    acceptedEncodings.length === 0 &&
    acceptedLanguages.length === 0 &&
    acceptedMediaRanges.length === 0;
 
  return isUndefined
    ? none
    : {
        acceptedCharsets,
        acceptedEncodings,
        acceptedLanguages,
        acceptedMediaRanges,
      };
};
 
export const createHttpPreferences = ({
  acceptedCharsets = [],
  acceptedEncodings = [],
  acceptedLanguages = [],
  acceptedMediaRanges = [],
}: {
  acceptedCharsets?: readonly string[];
  acceptedEncodings?: readonly HttpContentEncoding[];
  acceptedLanguages?: readonly string[];
  acceptedMediaRanges?: readonly (string | MediaRange)[];
}): HttpPreferences => {
  if (
    [
      acceptedCharsets,
      acceptedEncodings,
      acceptedLanguages,
      acceptedMediaRanges,
    ].findIndex(x => x.length > 0) < 0
  ) {
    throw new Error();
  }
 
  return {
    acceptedCharsets,
    acceptedEncodings,
    acceptedLanguages,
    acceptedMediaRanges: pipe(
      acceptedMediaRanges,
      mapReadonlyArray(mr =>
        typeof mr === "string" ? parseMediaTypeOrThrow(mr) : mr,
      ),
    ),
  };
};
 
const writeWeightedTokenHeader = (
  header: HttpStandardHeader,
  values: readonly string[],
  writeHeader: SideEffect2<string, string>,
) => {
  const length = values.length;
  if (length > 0) {
    const increment = 1000 / length;
 
    let result = "";
    for (let i = 0; i < length; i++) {
      result += values[i];
 
      if (i > 0) {
        const q = (i * increment) / 1000;
        result += `; q=${q.toFixed(1)}`;
      }
 
      if (i < length - 1) {
        result += ", ";
      }
    }
    writeHeader(header, result);
  }
};
 
export const writeHttpPreferenceHeaders = (
  preferences: HttpPreferences,
  writeHeader: SideEffect2<string, string>,
) => {
  const {
    acceptedCharsets,
    acceptedEncodings,
    acceptedLanguages,
    acceptedMediaRanges,
  } = preferences;
 
  writeWeightedTokenHeader(
    HttpStandardHeader.AcceptCharset,
    acceptedCharsets,
    writeHeader,
  );
  writeWeightedTokenHeader(
    HttpStandardHeader.AcceptEncoding,
    acceptedEncodings,
    writeHeader,
  );
  writeWeightedTokenHeader(
    HttpStandardHeader.AcceptLanguage,
    acceptedLanguages,
    writeHeader,
  );
 
  const tokenizedMediaRanges = pipe(
    acceptedMediaRanges,
    mapReadonlyArray(({ type, subtype }) => `${type}/${subtype}`),
  );
  writeWeightedTokenHeader(
    HttpStandardHeader.Accept,
    tokenizedMediaRanges,
    writeHeader,
  );
};