1 | import { getUserAgentPrefix } from "@aws-sdk/util-endpoints";
|
2 | import { HttpRequest } from "@smithy/protocol-http";
|
3 | import { SPACE, UA_ESCAPE_CHAR, UA_NAME_ESCAPE_REGEX, UA_NAME_SEPARATOR, UA_VALUE_ESCAPE_REGEX, USER_AGENT, X_AMZ_USER_AGENT, } from "./constants";
|
4 | export const userAgentMiddleware = (options) => (next, context) => async (args) => {
|
5 | const { request } = args;
|
6 | if (!HttpRequest.isInstance(request))
|
7 | return next(args);
|
8 | const { headers } = request;
|
9 | const userAgent = context?.userAgent?.map(escapeUserAgent) || [];
|
10 | const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
|
11 | const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
|
12 | const prefix = getUserAgentPrefix();
|
13 | const sdkUserAgentValue = (prefix ? [prefix] : [])
|
14 | .concat([...defaultUserAgent, ...userAgent, ...customUserAgent])
|
15 | .join(SPACE);
|
16 | const normalUAValue = [
|
17 | ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
|
18 | ...customUserAgent,
|
19 | ].join(SPACE);
|
20 | if (options.runtime !== "browser") {
|
21 | if (normalUAValue) {
|
22 | headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT]
|
23 | ? `${headers[USER_AGENT]} ${normalUAValue}`
|
24 | : normalUAValue;
|
25 | }
|
26 | headers[USER_AGENT] = sdkUserAgentValue;
|
27 | }
|
28 | else {
|
29 | headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
|
30 | }
|
31 | return next({
|
32 | ...args,
|
33 | request,
|
34 | });
|
35 | };
|
36 | const escapeUserAgent = (userAgentPair) => {
|
37 | const name = userAgentPair[0]
|
38 | .split(UA_NAME_SEPARATOR)
|
39 | .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR))
|
40 | .join(UA_NAME_SEPARATOR);
|
41 | const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
|
42 | const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
|
43 | const prefix = name.substring(0, prefixSeparatorIndex);
|
44 | let uaName = name.substring(prefixSeparatorIndex + 1);
|
45 | if (prefix === "api") {
|
46 | uaName = uaName.toLowerCase();
|
47 | }
|
48 | return [prefix, uaName, version]
|
49 | .filter((item) => item && item.length > 0)
|
50 | .reduce((acc, item, index) => {
|
51 | switch (index) {
|
52 | case 0:
|
53 | return item;
|
54 | case 1:
|
55 | return `${acc}/${item}`;
|
56 | default:
|
57 | return `${acc}#${item}`;
|
58 | }
|
59 | }, "");
|
60 | };
|
61 | export const getUserAgentMiddlewareOptions = {
|
62 | name: "getUserAgentMiddleware",
|
63 | step: "build",
|
64 | priority: "low",
|
65 | tags: ["SET_USER_AGENT", "USER_AGENT"],
|
66 | override: true,
|
67 | };
|
68 | export const getUserAgentPlugin = (config) => ({
|
69 | applyToStack: (clientStack) => {
|
70 | clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
|
71 | },
|
72 | });
|