@webiny/aws-helpers 0.0.0-unstable.79032b23a5 → 0.0.0-unstable.7be00a75a9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +2 -7
  2. package/README.md +11 -0
  3. package/cloudfrontFunctions/cookies.d.ts +8 -0
  4. package/cloudfrontFunctions/cookies.js +19 -0
  5. package/cloudfrontFunctions/cookies.js.map +1 -0
  6. package/cloudfrontFunctions/headers.d.ts +5 -0
  7. package/cloudfrontFunctions/headers.js +25 -0
  8. package/cloudfrontFunctions/headers.js.map +1 -0
  9. package/cloudfrontFunctions/index.d.ts +6 -0
  10. package/cloudfrontFunctions/index.js +6 -0
  11. package/cloudfrontFunctions/querystring.d.ts +2 -0
  12. package/cloudfrontFunctions/querystring.js +21 -0
  13. package/cloudfrontFunctions/querystring.js.map +1 -0
  14. package/cloudfrontFunctions/redirect.d.ts +8 -0
  15. package/cloudfrontFunctions/redirect.js +20 -0
  16. package/cloudfrontFunctions/redirect.js.map +1 -0
  17. package/cloudfrontFunctions/types.d.ts +78 -0
  18. package/cloudfrontFunctions/types.js +0 -0
  19. package/cloudfrontFunctions/utils.d.ts +17 -0
  20. package/cloudfrontFunctions/utils.js +10 -0
  21. package/cloudfrontFunctions/utils.js.map +1 -0
  22. package/index.d.ts +1 -0
  23. package/index.js +1 -0
  24. package/lambdaEdge/cookies.d.ts +3 -0
  25. package/lambdaEdge/cookies.js +22 -0
  26. package/lambdaEdge/cookies.js.map +1 -0
  27. package/lambdaEdge/headers.d.ts +6 -0
  28. package/lambdaEdge/headers.js +11 -0
  29. package/lambdaEdge/headers.js.map +1 -0
  30. package/lambdaEdge/index.d.ts +7 -0
  31. package/lambdaEdge/index.js +7 -0
  32. package/lambdaEdge/redirect.d.ts +8 -0
  33. package/lambdaEdge/redirect.js +32 -0
  34. package/lambdaEdge/redirect.js.map +1 -0
  35. package/lambdaEdge/request.d.ts +2 -0
  36. package/lambdaEdge/request.js +26 -0
  37. package/lambdaEdge/request.js.map +1 -0
  38. package/lambdaEdge/response.d.ts +2 -0
  39. package/lambdaEdge/response.js +10 -0
  40. package/lambdaEdge/response.js.map +1 -0
  41. package/lambdaEdge/types.d.ts +10 -0
  42. package/lambdaEdge/types.js +0 -0
  43. package/lambdaEdge/utils.d.ts +3 -0
  44. package/lambdaEdge/utils.js +9 -0
  45. package/lambdaEdge/utils.js.map +1 -0
  46. package/package.json +11 -8
  47. package/rslib-runtime.js +14 -0
  48. package/rslib-runtime.js.map +1 -0
  49. package/stagedRollouts/functions/adminOriginRequest.d.ts +2 -0
  50. package/stagedRollouts/functions/adminOriginRequest.js +26 -0
  51. package/stagedRollouts/functions/adminOriginRequest.js.map +1 -0
  52. package/stagedRollouts/functions/configOriginRequest.d.ts +2 -0
  53. package/stagedRollouts/functions/configOriginRequest.js +52 -0
  54. package/stagedRollouts/functions/configOriginRequest.js.map +1 -0
  55. package/stagedRollouts/functions/originRequest.d.ts +2 -0
  56. package/stagedRollouts/functions/originRequest.js +16 -0
  57. package/stagedRollouts/functions/originRequest.js.map +1 -0
  58. package/stagedRollouts/functions/viewerRequest.d.ts +1 -0
  59. package/stagedRollouts/functions/viewerRequest.js +22 -0
  60. package/stagedRollouts/functions/viewerRequest.js.map +1 -0
  61. package/stagedRollouts/functions/viewerResponse.d.ts +1 -0
  62. package/stagedRollouts/functions/viewerResponse.js +14 -0
  63. package/stagedRollouts/functions/viewerResponse.js.map +1 -0
  64. package/stagedRollouts/utils/common.d.ts +3 -0
  65. package/stagedRollouts/utils/common.js +8 -0
  66. package/stagedRollouts/utils/common.js.map +1 -0
  67. package/stagedRollouts/utils/headerBlacklist.d.ts +5 -0
  68. package/stagedRollouts/utils/headerBlacklist.js +31 -0
  69. package/stagedRollouts/utils/headerBlacklist.js.map +1 -0
  70. package/stagedRollouts/utils/loadOriginPage.d.ts +8 -0
  71. package/stagedRollouts/utils/loadOriginPage.js +84 -0
  72. package/stagedRollouts/utils/loadOriginPage.js.map +1 -0
  73. package/stagedRollouts/utils/loadTrafficSplittingConfig.d.ts +12 -0
  74. package/stagedRollouts/utils/loadTrafficSplittingConfig.js +47 -0
  75. package/stagedRollouts/utils/loadTrafficSplittingConfig.js.map +1 -0
  76. package/stagedRollouts/utils/loadVariantOrigin.d.ts +4 -0
  77. package/stagedRollouts/utils/loadVariantOrigin.js +51 -0
  78. package/stagedRollouts/utils/loadVariantOrigin.js.map +1 -0
  79. package/stagedRollouts/utils/log.d.ts +1 -0
  80. package/stagedRollouts/utils/log.js +6 -0
  81. package/stagedRollouts/utils/log.js.map +1 -0
package/LICENSE CHANGED
@@ -1,11 +1,6 @@
1
- Copyright (c) Webiny Inc.
1
+ MIT License
2
2
 
3
- Portions of this software are licensed as follows:
4
-
5
- * All content that resides under the "enterprise/" directories of this repository, is licensed under the license defined in their respective "enterprise/LICENSE" file.
6
- * All content that resides under the "packages/" sub-directories of this repository, is licensed under the license defined in their respective "packages/*/LICENSE" file.
7
- * All third party components incorporated into the Webiny Software are licensed under the original license provided by the owner of the applicable component.
8
- * Content outside of the above mentioned directories or restrictions above is available under the "MIT" license as defined below.
3
+ Copyright (c) Webiny
9
4
 
10
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
11
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @webiny/aws-helpers
2
+
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ 📘 **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -0,0 +1,8 @@
1
+ import type { CloudFrontResponse } from "./types.js";
2
+ export interface CookieParams {
3
+ name: string;
4
+ value: string;
5
+ maxAge?: number;
6
+ }
7
+ /** Sets cookie for the HTTP response */
8
+ export declare function setResponseCookie(response: CloudFrontResponse, cookie: CookieParams): void;
@@ -0,0 +1,19 @@
1
+ function setResponseCookie(response, cookie) {
2
+ const cookies = response.cookies || (response.cookies = {});
3
+ const current = cookies[cookie.name];
4
+ let attrs = "Secure; Path=/;";
5
+ if (cookie.maxAge) attrs += ` Max-Age=${cookie.maxAge};`;
6
+ if (current) {
7
+ const multivalue = current.multivalue ?? (current.multivalue = []);
8
+ multivalue.push({
9
+ value: cookie.value,
10
+ attributes: attrs
11
+ });
12
+ } else cookies[cookie.name] = {
13
+ value: cookie.value,
14
+ attributes: attrs
15
+ };
16
+ }
17
+ export { setResponseCookie };
18
+
19
+ //# sourceMappingURL=cookies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudfrontFunctions/cookies.js","sources":["../../src/cloudfrontFunctions/cookies.ts"],"sourcesContent":["import type { CloudFrontResponse } from \"./types.js\";\n\nexport interface CookieParams {\n name: string;\n value: string;\n maxAge?: number;\n}\n\n/** Sets cookie for the HTTP response */\nexport function setResponseCookie(response: CloudFrontResponse, cookie: CookieParams) {\n const cookies = response.cookies || (response.cookies = {});\n\n const current = cookies[cookie.name];\n let attrs = `Secure; Path=/;`;\n\n if (cookie.maxAge) {\n attrs += ` Max-Age=${cookie.maxAge};`;\n }\n\n if (current) {\n // If there is already the same cookie set in a response,\n // we add another entry using `multivalue`.\n // This is how you set multiple same cookies in CloudFront Functions.\n // It DOES make sense to set the same cookie multiple times,\n // for example when dealing with SameSite issue (https://web.dev/samesite-cookies-explained/)\n const multivalue = current.multivalue ?? (current.multivalue = []);\n multivalue.push({\n value: cookie.value,\n attributes: attrs\n });\n } else {\n cookies[cookie.name] = {\n value: cookie.value,\n attributes: attrs\n };\n }\n}\n"],"names":["setResponseCookie","response","cookie","cookies","current","attrs","multivalue"],"mappings":"AASO,SAASA,kBAAkBC,QAA4B,EAAEC,MAAoB;IAChF,MAAMC,UAAUF,SAAS,OAAO,IAAKA,CAAAA,SAAS,OAAO,GAAG,CAAC;IAEzD,MAAMG,UAAUD,OAAO,CAACD,OAAO,IAAI,CAAC;IACpC,IAAIG,QAAQ;IAEZ,IAAIH,OAAO,MAAM,EACbG,SAAS,CAAC,SAAS,EAAEH,OAAO,MAAM,CAAC,CAAC,CAAC;IAGzC,IAAIE,SAAS;QAMT,MAAME,aAAaF,QAAQ,UAAU,IAAKA,CAAAA,QAAQ,UAAU,GAAG,EAAC;QAChEE,WAAW,IAAI,CAAC;YACZ,OAAOJ,OAAO,KAAK;YACnB,YAAYG;QAChB;IACJ,OACIF,OAAO,CAACD,OAAO,IAAI,CAAC,GAAG;QACnB,OAAOA,OAAO,KAAK;QACnB,YAAYG;IAChB;AAER"}
@@ -0,0 +1,5 @@
1
+ import type { CloudFrontHeaders, Header } from "./types.js";
2
+ export declare function getHeader(headers: CloudFrontHeaders, header: string): string | undefined;
3
+ export declare function setHeader(headers: CloudFrontHeaders, header: Header): void;
4
+ export declare function setHeaders(headers: CloudFrontHeaders, headersToSet: Header[]): void;
5
+ export declare function setNoCacheHeaders(headers: CloudFrontHeaders): void;
@@ -0,0 +1,25 @@
1
+ function getHeader(headers, header) {
2
+ return headers[header]?.value;
3
+ }
4
+ function setHeader(headers, header) {
5
+ headers[header.key] = {
6
+ value: header.value
7
+ };
8
+ }
9
+ function setHeaders(headers, headersToSet) {
10
+ for(let i = 0; i < headersToSet.length; i++)setHeader(headers, headersToSet[i]);
11
+ }
12
+ function setNoCacheHeaders(headers) {
13
+ headers["cache-control"] = {
14
+ value: "no-cache, no-store, must-revalidate"
15
+ };
16
+ headers["pragma"] = {
17
+ value: "no-cache"
18
+ };
19
+ headers["expires"] = {
20
+ value: "0"
21
+ };
22
+ }
23
+ export { getHeader, setHeader, setHeaders, setNoCacheHeaders };
24
+
25
+ //# sourceMappingURL=headers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudfrontFunctions/headers.js","sources":["../../src/cloudfrontFunctions/headers.ts"],"sourcesContent":["import type { CloudFrontHeaders, Header } from \"./types.js\";\n\nexport function getHeader(headers: CloudFrontHeaders, header: string) {\n return headers[header]?.value;\n}\n\nexport function setHeader(headers: CloudFrontHeaders, header: Header) {\n headers[header.key] = {\n value: header.value\n };\n}\n\nexport function setHeaders(headers: CloudFrontHeaders, headersToSet: Header[]) {\n for (let i = 0; i < headersToSet.length; i++) {\n setHeader(headers, headersToSet[i]);\n }\n}\n\nexport function setNoCacheHeaders(headers: CloudFrontHeaders) {\n headers[\"cache-control\"] = { value: \"no-cache, no-store, must-revalidate\" };\n headers[\"pragma\"] = { value: \"no-cache\" };\n headers[\"expires\"] = { value: \"0\" };\n}\n"],"names":["getHeader","headers","header","setHeader","setHeaders","headersToSet","i","setNoCacheHeaders"],"mappings":"AAEO,SAASA,UAAUC,OAA0B,EAAEC,MAAc;IAChE,OAAOD,OAAO,CAACC,OAAO,EAAE;AAC5B;AAEO,SAASC,UAAUF,OAA0B,EAAEC,MAAc;IAChED,OAAO,CAACC,OAAO,GAAG,CAAC,GAAG;QAClB,OAAOA,OAAO,KAAK;IACvB;AACJ;AAEO,SAASE,WAAWH,OAA0B,EAAEI,YAAsB;IACzE,IAAK,IAAIC,IAAI,GAAGA,IAAID,aAAa,MAAM,EAAEC,IACrCH,UAAUF,SAASI,YAAY,CAACC,EAAE;AAE1C;AAEO,SAASC,kBAAkBN,OAA0B;IACxDA,OAAO,CAAC,gBAAgB,GAAG;QAAE,OAAO;IAAsC;IAC1EA,OAAO,CAAC,SAAS,GAAG;QAAE,OAAO;IAAW;IACxCA,OAAO,CAAC,UAAU,GAAG;QAAE,OAAO;IAAI;AACtC"}
@@ -0,0 +1,6 @@
1
+ export * from "./cookies.js";
2
+ export * from "./headers.js";
3
+ export * from "./querystring.js";
4
+ export * from "./redirect.js";
5
+ export * from "./types.js";
6
+ export * from "./utils.js";
@@ -0,0 +1,6 @@
1
+ export * from "./cookies.js";
2
+ export * from "./headers.js";
3
+ export * from "./querystring.js";
4
+ export * from "./redirect.js";
5
+ export * from "./types.js";
6
+ export * from "./utils.js";
@@ -0,0 +1,2 @@
1
+ import type { CloudFrontQuery } from "./types.js";
2
+ export declare function stringifyQuery(query: CloudFrontQuery): string;
@@ -0,0 +1,21 @@
1
+ function stringifyQuery(query) {
2
+ let qs = "";
3
+ for (const key of Object.keys(query)){
4
+ const value = query[key];
5
+ if (value) {
6
+ qs = appendQueryString(qs, key, value?.value);
7
+ if (value.multivalue) for(let i = 0; i < value.multivalue.length; i++)qs = appendQueryString(qs, key, value.multivalue[i].value);
8
+ }
9
+ }
10
+ if (qs) qs = "?" + qs;
11
+ return qs;
12
+ }
13
+ function appendQueryString(qs, key, value) {
14
+ if (null === value) return qs;
15
+ if (qs.length) qs += "&";
16
+ qs += `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
17
+ return qs;
18
+ }
19
+ export { stringifyQuery };
20
+
21
+ //# sourceMappingURL=querystring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudfrontFunctions/querystring.js","sources":["../../src/cloudfrontFunctions/querystring.ts"],"sourcesContent":["import type { CloudFrontQuery } from \"./types.js\";\n\nexport function stringifyQuery(query: CloudFrontQuery) {\n let qs = \"\";\n\n for (const key of Object.keys(query)) {\n const value = query[key];\n if (!value) {\n continue;\n }\n\n qs = appendQueryString(qs, key, value?.value);\n\n if (value.multivalue) {\n for (let i = 0; i < value.multivalue.length; i++) {\n qs = appendQueryString(qs, key, value.multivalue[i].value);\n }\n }\n }\n\n if (qs) {\n qs = \"?\" + qs;\n }\n\n return qs;\n}\n\nfunction appendQueryString(qs: string, key: string, value: string | null) {\n if (value === null) {\n return qs;\n }\n\n if (qs.length) {\n qs += \"&\";\n }\n\n qs += `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n\n return qs;\n}\n"],"names":["stringifyQuery","query","qs","key","Object","value","appendQueryString","i","encodeURIComponent"],"mappings":"AAEO,SAASA,eAAeC,KAAsB;IACjD,IAAIC,KAAK;IAET,KAAK,MAAMC,OAAOC,OAAO,IAAI,CAACH,OAAQ;QAClC,MAAMI,QAAQJ,KAAK,CAACE,IAAI;QACxB,IAAKE;YAILH,KAAKI,kBAAkBJ,IAAIC,KAAKE,OAAO;YAEvC,IAAIA,MAAM,UAAU,EAChB,IAAK,IAAIE,IAAI,GAAGA,IAAIF,MAAM,UAAU,CAAC,MAAM,EAAEE,IACzCL,KAAKI,kBAAkBJ,IAAIC,KAAKE,MAAM,UAAU,CAACE,EAAE,CAAC,KAAK;;IAGrE;IAEA,IAAIL,IACAA,KAAK,MAAMA;IAGf,OAAOA;AACX;AAEA,SAASI,kBAAkBJ,EAAU,EAAEC,GAAW,EAAEE,KAAoB;IACpE,IAAIA,AAAU,SAAVA,OACA,OAAOH;IAGX,IAAIA,GAAG,MAAM,EACTA,MAAM;IAGVA,MAAM,GAAGM,mBAAmBL,KAAK,CAAC,EAAEK,mBAAmBH,QAAQ;IAE/D,OAAOH;AACX"}
@@ -0,0 +1,8 @@
1
+ import type { CloudFrontQuery, CloudFrontResponse } from "./types.js";
2
+ interface RedirectParams {
3
+ url: string;
4
+ query?: CloudFrontQuery;
5
+ status?: number;
6
+ }
7
+ export declare function redirectResponse(params: RedirectParams): CloudFrontResponse;
8
+ export {};
@@ -0,0 +1,20 @@
1
+ import { setNoCacheHeaders } from "./headers.js";
2
+ import { stringifyQuery } from "./querystring.js";
3
+ function redirectResponse(params) {
4
+ const query = params.query ? stringifyQuery(params.query) : "";
5
+ const permanent = 301 === params.status;
6
+ const response = {
7
+ statusCode: params.status || 302,
8
+ statusDescription: 301 === params.status ? "Moved permanently" : "Found",
9
+ headers: {
10
+ location: {
11
+ value: params.url + query
12
+ }
13
+ }
14
+ };
15
+ if (!permanent) setNoCacheHeaders(response.headers);
16
+ return response;
17
+ }
18
+ export { redirectResponse };
19
+
20
+ //# sourceMappingURL=redirect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudfrontFunctions/redirect.js","sources":["../../src/cloudfrontFunctions/redirect.ts"],"sourcesContent":["import type { CloudFrontQuery, CloudFrontResponse } from \"./types.js\";\nimport { setNoCacheHeaders } from \"./headers.js\";\nimport { stringifyQuery } from \"./querystring.js\";\n\ninterface RedirectParams {\n url: string;\n query?: CloudFrontQuery;\n status?: number;\n}\n\nexport function redirectResponse(params: RedirectParams) {\n const query = params.query ? stringifyQuery(params.query) : \"\";\n const permanent = params.status === 301;\n\n const response: CloudFrontResponse = {\n statusCode: params.status || 302,\n statusDescription: params.status === 301 ? \"Moved permanently\" : \"Found\",\n headers: {\n location: { value: params.url + query }\n }\n };\n\n if (!permanent) {\n // For temporary redirects make sure they won't be cached.\n setNoCacheHeaders(response.headers);\n }\n\n return response;\n}\n"],"names":["redirectResponse","params","query","stringifyQuery","permanent","response","setNoCacheHeaders"],"mappings":";;AAUO,SAASA,iBAAiBC,MAAsB;IACnD,MAAMC,QAAQD,OAAO,KAAK,GAAGE,eAAeF,OAAO,KAAK,IAAI;IAC5D,MAAMG,YAAYH,AAAkB,QAAlBA,OAAO,MAAM;IAE/B,MAAMI,WAA+B;QACjC,YAAYJ,OAAO,MAAM,IAAI;QAC7B,mBAAmBA,AAAkB,QAAlBA,OAAO,MAAM,GAAW,sBAAsB;QACjE,SAAS;YACL,UAAU;gBAAE,OAAOA,OAAO,GAAG,GAAGC;YAAM;QAC1C;IACJ;IAEA,IAAI,CAACE,WAEDE,kBAAkBD,SAAS,OAAO;IAGtC,OAAOA;AACX"}
@@ -0,0 +1,78 @@
1
+ export interface SingleValue {
2
+ value: string;
3
+ }
4
+ export interface Header extends SingleValue {
5
+ key: string;
6
+ }
7
+ export interface ResponseCookie extends SingleValue {
8
+ attributes?: string;
9
+ }
10
+ /**
11
+ * In principle you may have multiple same headers and cookies in one request or response.
12
+ * This is a wrapper interface for simpler use.
13
+ */
14
+ export type MultiValue<T> = T & {
15
+ /** Additional values for the same item (for example multiple values for the same cookie.) */
16
+ multivalue?: T[];
17
+ };
18
+ export type MultiValueDictionary<T> = Record<string, MultiValue<T> | undefined>;
19
+ export type CloudFrontHeaders = MultiValueDictionary<SingleValue>;
20
+ export type CloudFrontRequestCookies = MultiValueDictionary<SingleValue>;
21
+ export type CloudFrontResponseCookies = MultiValueDictionary<ResponseCookie>;
22
+ export type CloudFrontQuery = MultiValueDictionary<SingleValue>;
23
+ /**
24
+ * Interface type for request in CloudFront Functions
25
+ * see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html
26
+ */
27
+ export interface CloudFrontRequest {
28
+ method: string;
29
+ uri: string;
30
+ querystring?: CloudFrontQuery;
31
+ headers: CloudFrontHeaders;
32
+ cookies?: CloudFrontRequestCookies;
33
+ }
34
+ /**
35
+ * Interface type for response in CloudFront Functions
36
+ * see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html
37
+ */
38
+ export interface CloudFrontResponse {
39
+ statusCode: number;
40
+ statusDescription?: string;
41
+ headers: CloudFrontHeaders;
42
+ cookies?: CloudFrontResponseCookies;
43
+ }
44
+ /**
45
+ * Interface type for request event in CloudFront Functions
46
+ * see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html
47
+ */
48
+ export interface CloudFrontRequestEvent {
49
+ version: string;
50
+ context: {
51
+ eventType: "viewer-request";
52
+ };
53
+ viewer: {
54
+ ip: string;
55
+ };
56
+ request: CloudFrontRequest;
57
+ }
58
+ /**
59
+ * Interface type for response event in CloudFront Functions
60
+ * see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html
61
+ */
62
+ export interface CloudFrontResponseEvent {
63
+ version: string;
64
+ context: {
65
+ eventType: "viewer-response";
66
+ };
67
+ viewer: {
68
+ ip: string;
69
+ };
70
+ response: CloudFrontResponse;
71
+ request: CloudFrontRequest;
72
+ }
73
+ export interface CloudFrontRequestHandler {
74
+ (event: CloudFrontRequestEvent): CloudFrontRequest | CloudFrontResponse;
75
+ }
76
+ export interface CloudFrontResponseHandler {
77
+ (event: CloudFrontResponseEvent): CloudFrontResponse;
78
+ }
File without changes
@@ -0,0 +1,17 @@
1
+ import type { CloudFrontRequestHandler, CloudFrontResponseHandler } from "./types.js";
2
+ /**
3
+ * Helper function to easier define CloudFront Function request handler.
4
+ *
5
+ * Lambdas use exports, but CloudFront Functions use a global `handler` variable.
6
+ * This way you only have to run the function within your handler script,
7
+ * and you are provided with working handler and full typing.
8
+ **/
9
+ export declare function defineCloudfrontFunctionRequestHandler(handler: CloudFrontRequestHandler): void;
10
+ /**
11
+ * Helper function to easier define CloudFront Function response handler.
12
+ *
13
+ * Lambdas use exports, but CloudFront Functions use a global `handler` variable.
14
+ * This way you only have to run the function within your handler script,
15
+ * and you are provided with working handler and full typing.
16
+ **/
17
+ export declare function defineCloudfrontFunctionResponseHandler(handler: CloudFrontResponseHandler): void;
@@ -0,0 +1,10 @@
1
+ import { __webpack_require__ } from "../rslib-runtime.js";
2
+ function defineCloudfrontFunctionRequestHandler(handler) {
3
+ __webpack_require__.g.handler = handler;
4
+ }
5
+ function defineCloudfrontFunctionResponseHandler(handler) {
6
+ __webpack_require__.g.handler = handler;
7
+ }
8
+ export { defineCloudfrontFunctionRequestHandler, defineCloudfrontFunctionResponseHandler };
9
+
10
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudfrontFunctions/utils.js","sources":["../../src/cloudfrontFunctions/utils.ts"],"sourcesContent":["import type { CloudFrontRequestHandler, CloudFrontResponseHandler } from \"./types.js\";\n\ndeclare const global: typeof globalThis & {\n handler: CloudFrontRequestHandler | CloudFrontResponseHandler;\n};\n\n/**\n * Helper function to easier define CloudFront Function request handler.\n *\n * Lambdas use exports, but CloudFront Functions use a global `handler` variable.\n * This way you only have to run the function within your handler script,\n * and you are provided with working handler and full typing.\n **/\nexport function defineCloudfrontFunctionRequestHandler(handler: CloudFrontRequestHandler) {\n global.handler = handler;\n}\n\n/**\n * Helper function to easier define CloudFront Function response handler.\n *\n * Lambdas use exports, but CloudFront Functions use a global `handler` variable.\n * This way you only have to run the function within your handler script,\n * and you are provided with working handler and full typing.\n **/\nexport function defineCloudfrontFunctionResponseHandler(handler: CloudFrontResponseHandler) {\n global.handler = handler;\n}\n"],"names":["defineCloudfrontFunctionRequestHandler","handler","global","defineCloudfrontFunctionResponseHandler"],"mappings":";AAaO,SAASA,uCAAuCC,OAAiC;IACpFC,oBAAAA,CAAMA,CAAC,OAAO,GAAGD;AACrB;AASO,SAASE,wCAAwCF,OAAkC;IACtFC,oBAAAA,CAAMA,CAAC,OAAO,GAAGD;AACrB"}
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./lambdaEdge/index.js";
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./lambdaEdge/index.js";
@@ -0,0 +1,3 @@
1
+ import type { CloudFrontRequest, CloudFrontResponse } from "./types.js";
2
+ export declare function getRequestCookies(request: CloudFrontRequest): Record<string, string | undefined>;
3
+ export declare function setResponseCookie(response: CloudFrontResponse, cookie: string): void;
@@ -0,0 +1,22 @@
1
+ import { getHeader } from "./headers.js";
2
+ function getRequestCookies(request) {
3
+ const header = getHeader(request.headers, "cookie");
4
+ const cookies = {};
5
+ if (!header) return cookies;
6
+ const cookiesArray = decodeURIComponent(header).split(";");
7
+ for (const cookie of cookiesArray){
8
+ const [name, value] = cookie.trim().split("=");
9
+ cookies[name] = value;
10
+ }
11
+ return cookies;
12
+ }
13
+ function setResponseCookie(response, cookie) {
14
+ const headers = response.headers;
15
+ const cookies = headers["set-cookie"] || (headers["set-cookie"] = []);
16
+ cookies.push({
17
+ value: cookie
18
+ });
19
+ }
20
+ export { getRequestCookies, setResponseCookie };
21
+
22
+ //# sourceMappingURL=cookies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lambdaEdge/cookies.js","sources":["../../src/lambdaEdge/cookies.ts"],"sourcesContent":["import { getHeader } from \"./headers.js\";\nimport type { CloudFrontRequest, CloudFrontResponse } from \"./types.js\";\n\nexport function getRequestCookies(request: CloudFrontRequest) {\n const header = getHeader(request.headers, \"cookie\");\n const cookies: Record<string, string | undefined> = {};\n\n if (!header) {\n return cookies;\n }\n\n const cookiesArray = decodeURIComponent(header).split(\";\");\n\n for (const cookie of cookiesArray) {\n const [name, value] = cookie.trim().split(\"=\");\n cookies[name] = value;\n }\n\n return cookies;\n}\n\nexport function setResponseCookie(response: CloudFrontResponse, cookie: string) {\n const headers = response.headers;\n const cookies = headers[\"set-cookie\"] || (headers[\"set-cookie\"] = []);\n\n cookies.push({\n value: cookie\n });\n}\n"],"names":["getRequestCookies","request","header","getHeader","cookies","cookiesArray","decodeURIComponent","cookie","name","value","setResponseCookie","response","headers"],"mappings":";AAGO,SAASA,kBAAkBC,OAA0B;IACxD,MAAMC,SAASC,UAAUF,QAAQ,OAAO,EAAE;IAC1C,MAAMG,UAA8C,CAAC;IAErD,IAAI,CAACF,QACD,OAAOE;IAGX,MAAMC,eAAeC,mBAAmBJ,QAAQ,KAAK,CAAC;IAEtD,KAAK,MAAMK,UAAUF,aAAc;QAC/B,MAAM,CAACG,MAAMC,MAAM,GAAGF,OAAO,IAAI,GAAG,KAAK,CAAC;QAC1CH,OAAO,CAACI,KAAK,GAAGC;IACpB;IAEA,OAAOL;AACX;AAEO,SAASM,kBAAkBC,QAA4B,EAAEJ,MAAc;IAC1E,MAAMK,UAAUD,SAAS,OAAO;IAChC,MAAMP,UAAUQ,OAAO,CAAC,aAAa,IAAKA,CAAAA,OAAO,CAAC,aAAa,GAAG,EAAC;IAEnER,QAAQ,IAAI,CAAC;QACT,OAAOG;IACX;AACJ"}
@@ -0,0 +1,6 @@
1
+ import type { CloudFrontHeaders } from "./types.js";
2
+ export declare function setHeader(headers: CloudFrontHeaders, header: {
3
+ key: string;
4
+ value: string;
5
+ }): void;
6
+ export declare function getHeader(headers: CloudFrontHeaders | undefined, header: string): string | undefined;
@@ -0,0 +1,11 @@
1
+ function setHeader(headers, header) {
2
+ headers[header.key] = [
3
+ header
4
+ ];
5
+ }
6
+ function getHeader(headers, header) {
7
+ return headers?.[header]?.[0].value;
8
+ }
9
+ export { getHeader, setHeader };
10
+
11
+ //# sourceMappingURL=headers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lambdaEdge/headers.js","sources":["../../src/lambdaEdge/headers.ts"],"sourcesContent":["import type { CloudFrontHeaders } from \"./types.js\";\n\nexport function setHeader(headers: CloudFrontHeaders, header: { key: string; value: string }) {\n headers[header.key] = [header];\n}\n\nexport function getHeader(headers: CloudFrontHeaders | undefined, header: string) {\n return headers?.[header]?.[0].value;\n}\n"],"names":["setHeader","headers","header","getHeader"],"mappings":"AAEO,SAASA,UAAUC,OAA0B,EAAEC,MAAsC;IACxFD,OAAO,CAACC,OAAO,GAAG,CAAC,GAAG;QAACA;KAAO;AAClC;AAEO,SAASC,UAAUF,OAAsC,EAAEC,MAAc;IAC5E,OAAOD,SAAS,CAACC,OAAO,EAAE,CAAC,EAAE,CAAC;AAClC"}
@@ -0,0 +1,7 @@
1
+ export * from "./cookies.js";
2
+ export * from "./headers.js";
3
+ export * from "./redirect.js";
4
+ export * from "./request.js";
5
+ export * from "./response.js";
6
+ export * from "./types.js";
7
+ export * from "./utils.js";
@@ -0,0 +1,7 @@
1
+ export * from "./cookies.js";
2
+ export * from "./headers.js";
3
+ export * from "./redirect.js";
4
+ export * from "./request.js";
5
+ export * from "./response.js";
6
+ export * from "./types.js";
7
+ export * from "./utils.js";
@@ -0,0 +1,8 @@
1
+ import type { CloudFrontResponse } from "./types.js";
2
+ interface RedirectParams {
3
+ url: string;
4
+ query?: string;
5
+ status?: number;
6
+ }
7
+ export declare function redirectResponse(params: RedirectParams): CloudFrontResponse;
8
+ export {};
@@ -0,0 +1,32 @@
1
+ import { setHeader } from "./headers.js";
2
+ function redirectResponse(params) {
3
+ const query = params.query || "";
4
+ const permanent = 301 === params.status;
5
+ const response = {
6
+ status: String(params.status || 302),
7
+ statusDescription: permanent ? "Moved permanently" : "Found",
8
+ headers: {}
9
+ };
10
+ setHeader(response.headers, {
11
+ key: "location",
12
+ value: params.url + query
13
+ });
14
+ if (!permanent) {
15
+ setHeader(response.headers, {
16
+ key: "cache-control",
17
+ value: "no-cache, no-store, must-revalidate"
18
+ });
19
+ setHeader(response.headers, {
20
+ key: "pragma",
21
+ value: "no-cache"
22
+ });
23
+ setHeader(response.headers, {
24
+ key: "expires",
25
+ value: "0"
26
+ });
27
+ }
28
+ return response;
29
+ }
30
+ export { redirectResponse };
31
+
32
+ //# sourceMappingURL=redirect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lambdaEdge/redirect.js","sources":["../../src/lambdaEdge/redirect.ts"],"sourcesContent":["import type { CloudFrontResponse } from \"./types.js\";\nimport { setHeader } from \"./headers.js\";\n\ninterface RedirectParams {\n url: string;\n query?: string;\n status?: number;\n}\n\nexport function redirectResponse(params: RedirectParams): CloudFrontResponse {\n const query = params.query || \"\";\n const permanent = params.status === 301;\n\n const response: CloudFrontResponse = {\n status: String(params.status || 302),\n statusDescription: permanent ? \"Moved permanently\" : \"Found\",\n headers: {}\n };\n\n setHeader(response.headers, {\n key: \"location\",\n value: params.url + query\n });\n\n if (!permanent) {\n // for temporary redirects make sure they won't be cached\n setHeader(response.headers, {\n key: \"cache-control\",\n value: \"no-cache, no-store, must-revalidate\"\n });\n setHeader(response.headers, {\n key: \"pragma\",\n value: \"no-cache\"\n });\n setHeader(response.headers, {\n key: \"expires\",\n value: \"0\"\n });\n }\n\n return response;\n}\n"],"names":["redirectResponse","params","query","permanent","response","String","setHeader"],"mappings":";AASO,SAASA,iBAAiBC,MAAsB;IACnD,MAAMC,QAAQD,OAAO,KAAK,IAAI;IAC9B,MAAME,YAAYF,AAAkB,QAAlBA,OAAO,MAAM;IAE/B,MAAMG,WAA+B;QACjC,QAAQC,OAAOJ,OAAO,MAAM,IAAI;QAChC,mBAAmBE,YAAY,sBAAsB;QACrD,SAAS,CAAC;IACd;IAEAG,UAAUF,SAAS,OAAO,EAAE;QACxB,KAAK;QACL,OAAOH,OAAO,GAAG,GAAGC;IACxB;IAEA,IAAI,CAACC,WAAW;QAEZG,UAAUF,SAAS,OAAO,EAAE;YACxB,KAAK;YACL,OAAO;QACX;QACAE,UAAUF,SAAS,OAAO,EAAE;YACxB,KAAK;YACL,OAAO;QACX;QACAE,UAAUF,SAAS,OAAO,EAAE;YACxB,KAAK;YACL,OAAO;QACX;IACJ;IAEA,OAAOA;AACX"}
@@ -0,0 +1,2 @@
1
+ import type { CloudFrontRequest } from "./types.js";
2
+ export declare function setDomainOrigin(request: CloudFrontRequest, domain: string): void;
@@ -0,0 +1,26 @@
1
+ import { setHeader } from "./headers.js";
2
+ function setDomainOrigin(request, domain) {
3
+ request.origin = {
4
+ custom: {
5
+ domainName: domain,
6
+ port: 443,
7
+ protocol: "https",
8
+ path: "",
9
+ sslProtocols: [
10
+ "TLSv1",
11
+ "TLSv1.1",
12
+ "TLSv1.2"
13
+ ],
14
+ readTimeout: 5,
15
+ keepaliveTimeout: 5,
16
+ customHeaders: {}
17
+ }
18
+ };
19
+ setHeader(request.headers, {
20
+ key: "host",
21
+ value: domain
22
+ });
23
+ }
24
+ export { setDomainOrigin };
25
+
26
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lambdaEdge/request.js","sources":["../../src/lambdaEdge/request.ts"],"sourcesContent":["import { setHeader } from \"./headers.js\";\nimport type { CloudFrontRequest } from \"./types.js\";\n\nexport function setDomainOrigin(request: CloudFrontRequest, domain: string) {\n request.origin = {\n custom: {\n domainName: domain,\n port: 443,\n protocol: \"https\",\n path: \"\",\n sslProtocols: [\"TLSv1\", \"TLSv1.1\", \"TLSv1.2\"],\n readTimeout: 5,\n keepaliveTimeout: 5,\n customHeaders: {}\n }\n };\n\n setHeader(request.headers, {\n key: \"host\",\n value: domain\n });\n}\n"],"names":["setDomainOrigin","request","domain","setHeader"],"mappings":";AAGO,SAASA,gBAAgBC,OAA0B,EAAEC,MAAc;IACtED,QAAQ,MAAM,GAAG;QACb,QAAQ;YACJ,YAAYC;YACZ,MAAM;YACN,UAAU;YACV,MAAM;YACN,cAAc;gBAAC;gBAAS;gBAAW;aAAU;YAC7C,aAAa;YACb,kBAAkB;YAClB,eAAe,CAAC;QACpB;IACJ;IAEAC,UAAUF,QAAQ,OAAO,EAAE;QACvB,KAAK;QACL,OAAOC;IACX;AACJ"}
@@ -0,0 +1,2 @@
1
+ import type { CloudFrontResultResponse } from "./types.js";
2
+ export declare function notFoundResponse(message?: string): CloudFrontResultResponse;
@@ -0,0 +1,10 @@
1
+ function notFoundResponse(message) {
2
+ return {
3
+ status: "404",
4
+ statusDescription: "Not found",
5
+ body: message || "Not found"
6
+ };
7
+ }
8
+ export { notFoundResponse };
9
+
10
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lambdaEdge/response.js","sources":["../../src/lambdaEdge/response.ts"],"sourcesContent":["import type { CloudFrontResultResponse } from \"./types.js\";\n\nexport function notFoundResponse(message?: string): CloudFrontResultResponse {\n return {\n status: \"404\",\n statusDescription: \"Not found\",\n body: message || \"Not found\"\n };\n}\n"],"names":["notFoundResponse","message"],"mappings":"AAEO,SAASA,iBAAiBC,OAAgB;IAC7C,OAAO;QACH,QAAQ;QACR,mBAAmB;QACnB,MAAMA,WAAW;IACrB;AACJ"}
@@ -0,0 +1,10 @@
1
+ import type { CloudFrontEvent as BaseCloudFrontEvent, CloudFrontRequest as BaseCloudFrontRequest, CloudFrontRequestEvent as BaseCloudFrontRequestEvent, CloudFrontResponse as BaseCloudFrontResponse, CloudFrontResponseEvent as BaseCloudFrontResponseEvent, CloudFrontResultResponse as BaseCloudFrontResultResponse, CloudFrontHeaders as BaseCloudFrontHeaders } from "aws-lambda";
2
+ export type CloudFrontEvent = BaseCloudFrontEvent;
3
+ export type CloudFrontRequest = BaseCloudFrontRequest;
4
+ export type CloudFrontRequestEvent = BaseCloudFrontRequestEvent;
5
+ export type CloudFrontResponse = BaseCloudFrontResponse & {
6
+ body?: string;
7
+ };
8
+ export type CloudFrontResponseEvent = BaseCloudFrontResponseEvent;
9
+ export type CloudFrontResultResponse = BaseCloudFrontResultResponse;
10
+ export type CloudFrontHeaders = BaseCloudFrontHeaders;
File without changes
@@ -0,0 +1,3 @@
1
+ import type { CloudFrontRequestHandler, CloudFrontResponseHandler } from "aws-lambda";
2
+ export declare function defineLambdaEdgeRequestHandler(handler: CloudFrontRequestHandler): CloudFrontRequestHandler;
3
+ export declare function defineLambdaEdgeResponseHandler(handler: CloudFrontResponseHandler): CloudFrontResponseHandler;
@@ -0,0 +1,9 @@
1
+ function defineLambdaEdgeRequestHandler(handler) {
2
+ return handler;
3
+ }
4
+ function defineLambdaEdgeResponseHandler(handler) {
5
+ return handler;
6
+ }
7
+ export { defineLambdaEdgeRequestHandler, defineLambdaEdgeResponseHandler };
8
+
9
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lambdaEdge/utils.js","sources":["../../src/lambdaEdge/utils.ts"],"sourcesContent":["import type { CloudFrontRequestHandler, CloudFrontResponseHandler } from \"aws-lambda\";\n\nexport function defineLambdaEdgeRequestHandler(handler: CloudFrontRequestHandler) {\n return handler;\n}\n\nexport function defineLambdaEdgeResponseHandler(handler: CloudFrontResponseHandler) {\n return handler;\n}\n"],"names":["defineLambdaEdgeRequestHandler","handler","defineLambdaEdgeResponseHandler"],"mappings":"AAEO,SAASA,+BAA+BC,OAAiC;IAC5E,OAAOA;AACX;AAEO,SAASC,gCAAgCD,OAAkC;IAC9E,OAAOA;AACX"}
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@webiny/aws-helpers",
3
- "version": "0.0.0-unstable.79032b23a5",
3
+ "version": "0.0.0-unstable.7be00a75a9",
4
+ "type": "module",
4
5
  "types": "dist/index.d.ts",
5
6
  "exports": {
6
7
  ".": {
@@ -22,17 +23,16 @@
22
23
  "description": "An utility package for developing AWS based services",
23
24
  "license": "MIT",
24
25
  "publishConfig": {
25
- "access": "public",
26
- "directory": "dist"
26
+ "access": "public"
27
27
  },
28
- "gitHead": "79032b23a5e5b580fb21be88e8cc66d0dce7afdc",
28
+ "gitHead": "b8aec8a1be3f25c3b428b357fe1e352c7cbff9ae",
29
29
  "dependencies": {
30
- "@types/aws-lambda": "8.10.110",
31
- "cheerio": "1.0.0-rc.12",
32
- "srcset": "4.0.0"
30
+ "@types/aws-lambda": "8.10.161",
31
+ "cheerio": "1.2.0",
32
+ "srcset": "5.0.3"
33
33
  },
34
34
  "devDependencies": {
35
- "@webiny/project-utils": "^0.0.0-unstable.79032b23a5"
35
+ "@webiny/build-tools": "0.0.0-unstable.7be00a75a9"
36
36
  },
37
37
  "sideEffects": false,
38
38
  "adio": {
@@ -44,5 +44,8 @@
44
44
  "@types/aws-lambda"
45
45
  ]
46
46
  }
47
+ },
48
+ "webiny": {
49
+ "publishFrom": "dist"
47
50
  }
48
51
  }
@@ -0,0 +1,14 @@
1
+ var __webpack_require__ = {};
2
+ (()=>{
3
+ __webpack_require__.g = (()=>{
4
+ if ('object' == typeof globalThis) return globalThis;
5
+ try {
6
+ return this || new Function('return this')();
7
+ } catch (e) {
8
+ if ('object' == typeof window) return window;
9
+ }
10
+ })();
11
+ })();
12
+ export { __webpack_require__ };
13
+
14
+ //# sourceMappingURL=rslib-runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rslib-runtime.js","sources":["webpack://webpack/runtime/global"],"sourcesContent":["__webpack_require__.g = (() => {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();"],"names":["__webpack_require__","globalThis","Function","e","window"],"mappings":";;IAAAA,oBAAoB,CAAC,GAAG,AAAC;QACxB,IAAI,AAAsB,YAAtB,OAAOC,YAAyB,OAAOA;QAC3C,IAAI;YACH,OAAO,IAAI,IAAI,IAAIC,SAAS;QAC7B,EAAE,OAAOC,GAAG;YACX,IAAI,AAAkB,YAAlB,OAAOC,QAAqB,OAAOA;QACxC;IACD"}
@@ -0,0 +1,2 @@
1
+ declare const _default: import("aws-lambda").CloudFrontRequestHandler;
2
+ export default _default;
@@ -0,0 +1,26 @@
1
+ import { defineLambdaEdgeRequestHandler, setDomainOrigin } from "../../lambdaEdge/index.js";
2
+ import { pointsToFile } from "../utils/common.js";
3
+ import { loadOriginPage } from "../utils/loadOriginPage.js";
4
+ import { loadVariantOrigin } from "../utils/loadVariantOrigin.js";
5
+ const adminOriginRequest = defineLambdaEdgeRequestHandler(async (event)=>{
6
+ try {
7
+ const result = await loadVariantOrigin(event);
8
+ if ("variant" in result) {
9
+ const cf = event.Records[0].cf;
10
+ const request = cf.request;
11
+ const variant = result.variant;
12
+ if (pointsToFile(request.uri)) {
13
+ setDomainOrigin(request, variant.domain);
14
+ return request;
15
+ }
16
+ return await loadOriginPage(variant.domain, request.uri);
17
+ }
18
+ return result;
19
+ } catch (e) {
20
+ console.error(e);
21
+ throw e;
22
+ }
23
+ });
24
+ export default adminOriginRequest;
25
+
26
+ //# sourceMappingURL=adminOriginRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/functions/adminOriginRequest.js","sources":["../../../src/stagedRollouts/functions/adminOriginRequest.ts"],"sourcesContent":["import { defineLambdaEdgeRequestHandler, setDomainOrigin } from \"~/lambdaEdge/index.js\";\n\nimport { pointsToFile } from \"../utils/common.js\";\nimport { loadOriginPage } from \"../utils/loadOriginPage.js\";\nimport { loadVariantOrigin } from \"../utils/loadVariantOrigin.js\";\n\nexport default defineLambdaEdgeRequestHandler(async event => {\n try {\n const result = await loadVariantOrigin(event);\n\n if (\"variant\" in result) {\n const cf = event.Records[0].cf;\n const request = cf.request;\n const variant = result.variant;\n\n // For file requests we just pass the request to proper origin.\n if (pointsToFile(request.uri)) {\n setDomainOrigin(request, variant.domain);\n return request;\n }\n\n // For pages we make a custom HTTP request to the origin and transform page properly.\n // For example we change asset URLs to be absolute.\n return await loadOriginPage(variant.domain, request.uri);\n }\n return result;\n } catch (e) {\n console.error(e);\n throw e;\n }\n});\n"],"names":["defineLambdaEdgeRequestHandler","event","result","loadVariantOrigin","cf","request","variant","pointsToFile","setDomainOrigin","loadOriginPage","e","console"],"mappings":";;;;AAMA,2BAAeA,+BAA+B,OAAMC;IAChD,IAAI;QACA,MAAMC,SAAS,MAAMC,kBAAkBF;QAEvC,IAAI,aAAaC,QAAQ;YACrB,MAAME,KAAKH,MAAM,OAAO,CAAC,EAAE,CAAC,EAAE;YAC9B,MAAMI,UAAUD,GAAG,OAAO;YAC1B,MAAME,UAAUJ,OAAO,OAAO;YAG9B,IAAIK,aAAaF,QAAQ,GAAG,GAAG;gBAC3BG,gBAAgBH,SAASC,QAAQ,MAAM;gBACvC,OAAOD;YACX;YAIA,OAAO,MAAMI,eAAeH,QAAQ,MAAM,EAAED,QAAQ,GAAG;QAC3D;QACA,OAAOH;IACX,EAAE,OAAOQ,GAAG;QACRC,QAAQ,KAAK,CAACD;QACd,MAAMA;IACV;AACJ"}
@@ -0,0 +1,2 @@
1
+ declare const _default: import("aws-lambda").CloudFrontRequestHandler;
2
+ export default _default;
@@ -0,0 +1,52 @@
1
+ import { defineLambdaEdgeRequestHandler, setHeader } from "../../lambdaEdge/index.js";
2
+ import { get } from "https";
3
+ const configOriginRequest = defineLambdaEdgeRequestHandler(async (event)=>{
4
+ try {
5
+ const configJson = await loadConfigJson(event);
6
+ const response = {
7
+ status: "200",
8
+ statusDescription: "OK",
9
+ headers: {},
10
+ body: configJson
11
+ };
12
+ setHeader(response.headers, {
13
+ key: "Content-Type",
14
+ value: "application/json"
15
+ });
16
+ setHeader(response.headers, {
17
+ key: "Cache-Control",
18
+ value: "public, max-age=31536000"
19
+ });
20
+ return response;
21
+ } catch (e) {
22
+ console.error(e);
23
+ throw e;
24
+ }
25
+ });
26
+ function loadConfigJson(event) {
27
+ return new Promise((resolve, reject)=>{
28
+ let dataString = "";
29
+ const domain = event.Records[0].cf.config.distributionDomainName;
30
+ const req = get({
31
+ hostname: domain,
32
+ port: 443,
33
+ path: "/_config.json"
34
+ }, function(res) {
35
+ res.on("data", (chunk)=>{
36
+ dataString += chunk;
37
+ });
38
+ res.on("end", ()=>{
39
+ resolve(dataString);
40
+ });
41
+ });
42
+ req.on("error", (e)=>{
43
+ reject({
44
+ statusCode: 500,
45
+ body: e.message
46
+ });
47
+ });
48
+ });
49
+ }
50
+ export default configOriginRequest;
51
+
52
+ //# sourceMappingURL=configOriginRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/functions/configOriginRequest.js","sources":["../../../src/stagedRollouts/functions/configOriginRequest.ts"],"sourcesContent":["import type { CloudFrontRequestEvent, CloudFrontResponse } from \"~/lambdaEdge/index.js\";\nimport { defineLambdaEdgeRequestHandler, setHeader } from \"~/lambdaEdge/index.js\";\n\nimport { get } from \"https\";\n\nexport default defineLambdaEdgeRequestHandler(async event => {\n try {\n const configJson = await loadConfigJson(event);\n const response: CloudFrontResponse = {\n status: \"200\",\n statusDescription: \"OK\",\n headers: {},\n body: configJson\n };\n\n setHeader(response.headers, {\n key: \"Content-Type\",\n value: \"application/json\"\n });\n\n setHeader(response.headers, {\n key: \"Cache-Control\",\n value: \"public, max-age=31536000\"\n });\n\n return response;\n } catch (e) {\n console.error(e);\n throw e;\n }\n});\n\nfunction loadConfigJson(event: CloudFrontRequestEvent) {\n return new Promise<string>((resolve, reject) => {\n let dataString = \"\";\n\n // Retrieve domain of the CloudFront distribution.\n const domain = event.Records[0].cf.config.distributionDomainName;\n\n const req = get(\n {\n hostname: domain,\n port: 443,\n // TODO: we will call WCP instead of a static file here\n path: \"/_config.json\"\n },\n function (res) {\n res.on(\"data\", chunk => {\n dataString += chunk;\n });\n res.on(\"end\", () => {\n resolve(dataString);\n });\n }\n );\n\n req.on(\"error\", e => {\n reject({\n statusCode: 500,\n body: e.message\n });\n });\n });\n}\n"],"names":["defineLambdaEdgeRequestHandler","event","configJson","loadConfigJson","response","setHeader","e","console","Promise","resolve","reject","dataString","domain","req","get","res","chunk"],"mappings":";;AAKA,4BAAeA,+BAA+B,OAAMC;IAChD,IAAI;QACA,MAAMC,aAAa,MAAMC,eAAeF;QACxC,MAAMG,WAA+B;YACjC,QAAQ;YACR,mBAAmB;YACnB,SAAS,CAAC;YACV,MAAMF;QACV;QAEAG,UAAUD,SAAS,OAAO,EAAE;YACxB,KAAK;YACL,OAAO;QACX;QAEAC,UAAUD,SAAS,OAAO,EAAE;YACxB,KAAK;YACL,OAAO;QACX;QAEA,OAAOA;IACX,EAAE,OAAOE,GAAG;QACRC,QAAQ,KAAK,CAACD;QACd,MAAMA;IACV;AACJ;AAEA,SAASH,eAAeF,KAA6B;IACjD,OAAO,IAAIO,QAAgB,CAACC,SAASC;QACjC,IAAIC,aAAa;QAGjB,MAAMC,SAASX,MAAM,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,sBAAsB;QAEhE,MAAMY,MAAMC,IACR;YACI,UAAUF;YACV,MAAM;YAEN,MAAM;QACV,GACA,SAAUG,GAAG;YACTA,IAAI,EAAE,CAAC,QAAQC,CAAAA;gBACXL,cAAcK;YAClB;YACAD,IAAI,EAAE,CAAC,OAAO;gBACVN,QAAQE;YACZ;QACJ;QAGJE,IAAI,EAAE,CAAC,SAASP,CAAAA;YACZI,OAAO;gBACH,YAAY;gBACZ,MAAMJ,EAAE,OAAO;YACnB;QACJ;IACJ;AACJ"}
@@ -0,0 +1,2 @@
1
+ declare const _default: import("aws-lambda").CloudFrontRequestHandler;
2
+ export default _default;
@@ -0,0 +1,16 @@
1
+ import { defineLambdaEdgeRequestHandler, setDomainOrigin } from "../../lambdaEdge/index.js";
2
+ import { loadVariantOrigin } from "../utils/loadVariantOrigin.js";
3
+ const originRequest = defineLambdaEdgeRequestHandler(async (event)=>{
4
+ const result = await loadVariantOrigin(event);
5
+ if ("variant" in result) {
6
+ const cf = event.Records[0].cf;
7
+ const request = cf.request;
8
+ const variant = result.variant;
9
+ setDomainOrigin(request, variant.domain);
10
+ return request;
11
+ }
12
+ return result;
13
+ });
14
+ export default originRequest;
15
+
16
+ //# sourceMappingURL=originRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/functions/originRequest.js","sources":["../../../src/stagedRollouts/functions/originRequest.ts"],"sourcesContent":["import { defineLambdaEdgeRequestHandler, setDomainOrigin } from \"~/lambdaEdge/index.js\";\n\nimport { loadVariantOrigin } from \"../utils/loadVariantOrigin.js\";\n\nexport default defineLambdaEdgeRequestHandler(async event => {\n const result = await loadVariantOrigin(event);\n\n if (\"variant\" in result) {\n const cf = event.Records[0].cf;\n const request = cf.request;\n const variant = result.variant;\n\n setDomainOrigin(request, variant.domain);\n return request;\n }\n\n return result;\n});\n"],"names":["defineLambdaEdgeRequestHandler","event","result","loadVariantOrigin","cf","request","variant","setDomainOrigin"],"mappings":";;AAIA,sBAAeA,+BAA+B,OAAMC;IAChD,MAAMC,SAAS,MAAMC,kBAAkBF;IAEvC,IAAI,aAAaC,QAAQ;QACrB,MAAME,KAAKH,MAAM,OAAO,CAAC,EAAE,CAAC,EAAE;QAC9B,MAAMI,UAAUD,GAAG,OAAO;QAC1B,MAAME,UAAUJ,OAAO,OAAO;QAE9BK,gBAAgBF,SAASC,QAAQ,MAAM;QACvC,OAAOD;IACX;IAEA,OAAOH;AACX"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ import { defineCloudfrontFunctionRequestHandler } from "../../cloudfrontFunctions/index.js";
2
+ import { variantFixedKey, variantRandomKey } from "../utils/common.js";
3
+ defineCloudfrontFunctionRequestHandler((event)=>{
4
+ const request = event.request;
5
+ const variantFixed = request.cookies?.[variantFixedKey]?.value || request.headers[variantFixedKey]?.value;
6
+ if (variantFixed) {
7
+ request.headers[variantFixedKey] = {
8
+ value: variantFixed
9
+ };
10
+ delete request.headers[variantRandomKey];
11
+ return request;
12
+ }
13
+ let variantRandom = Number(request.cookies?.[variantRandomKey]?.value);
14
+ if (isNaN(variantRandom) || variantRandom < 1 || variantRandom > 100) variantRandom = Math.floor(100 * Math.random() + 1);
15
+ variantRandom -= variantRandom % 5;
16
+ request.headers[variantRandomKey] = {
17
+ value: variantRandom.toString()
18
+ };
19
+ return request;
20
+ });
21
+
22
+ //# sourceMappingURL=viewerRequest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/functions/viewerRequest.js","sources":["../../../src/stagedRollouts/functions/viewerRequest.ts"],"sourcesContent":["import { defineCloudfrontFunctionRequestHandler } from \"~/cloudfrontFunctions/index.js\";\n\nimport { variantFixedKey, variantRandomKey } from \"../utils/common.js\";\n\ndefineCloudfrontFunctionRequestHandler(event => {\n const request = event.request;\n\n // Try to get stage name from cookie or header.\n const variantFixed =\n request.cookies?.[variantFixedKey]?.value || request.headers[variantFixedKey]?.value;\n if (variantFixed) {\n // If there is a fixed variant set, we just pass it further to origin request handler.\n request.headers[variantFixedKey] = {\n value: variantFixed\n };\n\n // If variant is explicitly selected, remove any random header a user may have passed.\n // We want to have either one or another for better cache hit rate.\n delete request.headers[variantRandomKey];\n return request;\n }\n\n // Otherwise we try to retrieve randomized number from user cookie.\n // This random value will be passed further to the origin request to select based on config.\n let variantRandom = Number(request.cookies?.[variantRandomKey]?.value);\n if (isNaN(variantRandom) || variantRandom < 1 || variantRandom > 100) {\n // If no value is present we simply randomize one.\n // This formula gives you an integer 1-100 (inclusive).\n // This way we have exactly 100 possible values.\n // Math.random() return values in range [0, 1) - 0 inclusive, 1 exclusive.\n // So we need to adjust it a litte bit to achieve what we want.\n variantRandom = Math.floor(Math.random() * 100 + 1);\n }\n\n // Adjust random value to a specific interval optimize caching.\n // Less possible values means less separate cache entries in CDN an better cache hit ratio.\n // TODO this value can set during deployment, to allow users to decide on trade-off between better caching and finer traffic splitting\n variantRandom -= variantRandom % 5;\n\n request.headers[variantRandomKey] = {\n value: variantRandom.toString()\n };\n\n return request;\n});\n"],"names":["defineCloudfrontFunctionRequestHandler","event","request","variantFixed","variantFixedKey","variantRandomKey","variantRandom","Number","isNaN","Math"],"mappings":";;AAIAA,uCAAuCC,CAAAA;IACnC,MAAMC,UAAUD,MAAM,OAAO;IAG7B,MAAME,eACFD,QAAQ,OAAO,EAAE,CAACE,gBAAgB,EAAE,SAASF,QAAQ,OAAO,CAACE,gBAAgB,EAAE;IACnF,IAAID,cAAc;QAEdD,QAAQ,OAAO,CAACE,gBAAgB,GAAG;YAC/B,OAAOD;QACX;QAIA,OAAOD,QAAQ,OAAO,CAACG,iBAAiB;QACxC,OAAOH;IACX;IAIA,IAAII,gBAAgBC,OAAOL,QAAQ,OAAO,EAAE,CAACG,iBAAiB,EAAE;IAChE,IAAIG,MAAMF,kBAAkBA,gBAAgB,KAAKA,gBAAgB,KAM7DA,gBAAgBG,KAAK,KAAK,CAACA,AAAgB,MAAhBA,KAAK,MAAM,KAAW;IAMrDH,iBAAiBA,gBAAgB;IAEjCJ,QAAQ,OAAO,CAACG,iBAAiB,GAAG;QAChC,OAAOC,cAAc,QAAQ;IACjC;IAEA,OAAOJ;AACX"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import { defineCloudfrontFunctionResponseHandler, setResponseCookie } from "../../cloudfrontFunctions/index.js";
2
+ import { variantRandomKey } from "../utils/common.js";
3
+ defineCloudfrontFunctionResponseHandler((event)=>{
4
+ const request = event.request;
5
+ const response = event.response;
6
+ const variantRandom = request.headers[variantRandomKey]?.value;
7
+ if (variantRandom) setResponseCookie(response, {
8
+ name: variantRandomKey,
9
+ value: variantRandom
10
+ });
11
+ return response;
12
+ });
13
+
14
+ //# sourceMappingURL=viewerResponse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/functions/viewerResponse.js","sources":["../../../src/stagedRollouts/functions/viewerResponse.ts"],"sourcesContent":["import {\n defineCloudfrontFunctionResponseHandler,\n setResponseCookie\n} from \"~/cloudfrontFunctions/index.js\";\n\nimport { variantRandomKey } from \"../utils/common.js\";\n\ndefineCloudfrontFunctionResponseHandler(event => {\n const request = event.request;\n const response = event.response;\n\n const variantRandom = request.headers[variantRandomKey]?.value;\n if (variantRandom) {\n setResponseCookie(response, {\n name: variantRandomKey,\n value: variantRandom\n });\n }\n\n return response;\n});\n"],"names":["defineCloudfrontFunctionResponseHandler","event","request","response","variantRandom","variantRandomKey","setResponseCookie"],"mappings":";;AAOAA,wCAAwCC,CAAAA;IACpC,MAAMC,UAAUD,MAAM,OAAO;IAC7B,MAAME,WAAWF,MAAM,QAAQ;IAE/B,MAAMG,gBAAgBF,QAAQ,OAAO,CAACG,iBAAiB,EAAE;IACzD,IAAID,eACAE,kBAAkBH,UAAU;QACxB,MAAME;QACN,OAAOD;IACX;IAGJ,OAAOD;AACX"}
@@ -0,0 +1,3 @@
1
+ export declare const variantFixedKey = "webiny-variant-fixed";
2
+ export declare const variantRandomKey = "webiny-variant-random";
3
+ export declare function pointsToFile(uri: string): boolean;
@@ -0,0 +1,8 @@
1
+ const variantFixedKey = "webiny-variant-fixed";
2
+ const variantRandomKey = "webiny-variant-random";
3
+ function pointsToFile(uri) {
4
+ return /\/[^/]+\.[^/]+$/.test(uri);
5
+ }
6
+ export { pointsToFile, variantFixedKey, variantRandomKey };
7
+
8
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/utils/common.js","sources":["../../../src/stagedRollouts/utils/common.ts"],"sourcesContent":["export const variantFixedKey = \"webiny-variant-fixed\";\nexport const variantRandomKey = \"webiny-variant-random\";\n\nexport function pointsToFile(uri: string) {\n return /\\/[^/]+\\.[^/]+$/.test(uri);\n}\n"],"names":["variantFixedKey","variantRandomKey","pointsToFile","uri"],"mappings":"AAAO,MAAMA,kBAAkB;AACxB,MAAMC,mBAAmB;AAEzB,SAASC,aAAaC,GAAW;IACpC,OAAO,kBAAkB,IAAI,CAACA;AAClC"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Some headers cannot be modified with lambda edge.
3
+ * Source: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-restrictions.html
4
+ */
5
+ export declare function isHeaderBlacklisted(header: string): boolean;
@@ -0,0 +1,31 @@
1
+ const blacklistedHeaders = new Set([
2
+ "connection",
3
+ "expect",
4
+ "keep-Alive",
5
+ "proxy-authenticate",
6
+ "proxy-authorization",
7
+ "proxy-connection",
8
+ "trailer",
9
+ "upgrade",
10
+ "x-accel-buffering",
11
+ "x-accel-charset",
12
+ "x-accel-limit-rate",
13
+ "x-accel-redirect",
14
+ "x-cache",
15
+ "x-forwarded-proto",
16
+ "x-real-op",
17
+ "content-length",
18
+ "transfer-encoding",
19
+ "via"
20
+ ]);
21
+ const blacklistedHeadersRegex = [
22
+ /^x-amz-cf-/,
23
+ /^x-edge-/
24
+ ];
25
+ function isHeaderBlacklisted(header) {
26
+ header = header.toLocaleLowerCase();
27
+ return blacklistedHeaders.has(header) || blacklistedHeadersRegex.some((r)=>r.test(header));
28
+ }
29
+ export { isHeaderBlacklisted };
30
+
31
+ //# sourceMappingURL=headerBlacklist.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/utils/headerBlacklist.js","sources":["../../../src/stagedRollouts/utils/headerBlacklist.ts"],"sourcesContent":["const blacklistedHeaders = new Set([\n // blacklisted headers\n \"connection\",\n \"expect\",\n \"keep-Alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"trailer\",\n \"upgrade\",\n \"x-accel-buffering\",\n \"x-accel-charset\",\n \"x-accel-limit-rate\",\n \"x-accel-redirect\",\n \"x-cache\",\n \"x-forwarded-proto\",\n \"x-real-op\",\n // readonly headers\n \"content-length\",\n \"transfer-encoding\",\n \"via\"\n]);\n\nconst blacklistedHeadersRegex = [/^x-amz-cf-/, /^x-edge-/];\n\n/**\n * Some headers cannot be modified with lambda edge.\n * Source: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-restrictions.html\n */\nexport function isHeaderBlacklisted(header: string) {\n header = header.toLocaleLowerCase();\n return blacklistedHeaders.has(header) || blacklistedHeadersRegex.some(r => r.test(header));\n}\n"],"names":["blacklistedHeaders","Set","blacklistedHeadersRegex","isHeaderBlacklisted","header","r"],"mappings":"AAAA,MAAMA,qBAAqB,IAAIC,IAAI;IAE/B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;CACH;AAED,MAAMC,0BAA0B;IAAC;IAAc;CAAW;AAMnD,SAASC,oBAAoBC,MAAc;IAC9CA,SAASA,OAAO,iBAAiB;IACjC,OAAOJ,mBAAmB,GAAG,CAACI,WAAWF,wBAAwB,IAAI,CAACG,CAAAA,IAAKA,EAAE,IAAI,CAACD;AACtF"}
@@ -0,0 +1,8 @@
1
+ import type { CloudFrontResponse } from "../../lambdaEdge/index.js";
2
+ /**
3
+ * Load HTML from origin and perform transformation of URLs to absolute
4
+ * @param domain Domain of the origin cloudfront
5
+ * @param path Path of the file we want to retrieve
6
+ * @returns Response object
7
+ */
8
+ export declare function loadOriginPage(domain: string, path: string): Promise<CloudFrontResponse>;
@@ -0,0 +1,84 @@
1
+ import { get } from "https";
2
+ import { load } from "cheerio";
3
+ import { parseSrcset, stringifySrcset } from "srcset";
4
+ import { isHeaderBlacklisted } from "./headerBlacklist.js";
5
+ import { logDebug } from "./log.js";
6
+ function loadOriginPage(domain, path) {
7
+ return new Promise((resolve, reject)=>{
8
+ logDebug(`Pulling page from ${domain}${path}`);
9
+ let responseBody = "";
10
+ const req = get({
11
+ hostname: domain,
12
+ port: 443,
13
+ path: path
14
+ }, (res)=>{
15
+ res.on("data", (chunk)=>responseBody += chunk);
16
+ res.on("end", ()=>{
17
+ logDebug("Parsing page");
18
+ const html = parseHtml(responseBody, domain);
19
+ const response = {
20
+ body: html,
21
+ status: "200",
22
+ statusDescription: "ok",
23
+ headers: {}
24
+ };
25
+ for (const header of Object.keys(res.headers)){
26
+ if (isHeaderBlacklisted(header)) continue;
27
+ const value = res.headers[header];
28
+ if (Array.isArray(value)) response.headers[header] = value.map((h)=>({
29
+ key: header,
30
+ value: h
31
+ }));
32
+ else if (value) response.headers[header] = [
33
+ {
34
+ key: header,
35
+ value: value
36
+ }
37
+ ];
38
+ }
39
+ logDebug("Page parsed");
40
+ resolve(response);
41
+ });
42
+ });
43
+ req.on("error", (e)=>{
44
+ reject({
45
+ statusCode: 500,
46
+ body: e.message
47
+ });
48
+ });
49
+ });
50
+ }
51
+ function parseHtml(html, domain) {
52
+ const doc = load(html);
53
+ const host = `https://${domain}`;
54
+ doc("head > link").each((_i, el)=>{
55
+ prefixUrl(el, "href", host);
56
+ });
57
+ doc("script").each((_i, el)=>{
58
+ prefixUrl(el, "src", host);
59
+ });
60
+ doc("body").find("img").each((_i, el)=>{
61
+ prefixUrl(el, "src", host);
62
+ const srcset = el.attribs["srcset"];
63
+ if (srcset) {
64
+ const srcsetParsed = parseSrcset(srcset);
65
+ const srcsetRebased = srcsetParsed.map((src)=>{
66
+ if (src.url.startsWith("/")) return {
67
+ url: host + src.url,
68
+ density: src.density,
69
+ width: src.width
70
+ };
71
+ return src;
72
+ });
73
+ el.attribs["srcset"] = stringifySrcset(srcsetRebased);
74
+ }
75
+ });
76
+ return doc.html();
77
+ }
78
+ function prefixUrl(el, attr, host) {
79
+ const href = el.attribs[attr];
80
+ if (href && href.startsWith("/")) el.attribs[attr] = host + href;
81
+ }
82
+ export { loadOriginPage };
83
+
84
+ //# sourceMappingURL=loadOriginPage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/utils/loadOriginPage.js","sources":["../../../src/stagedRollouts/utils/loadOriginPage.ts"],"sourcesContent":["import type { CloudFrontResponse } from \"~/lambdaEdge/index.js\";\nimport { get } from \"https\";\nimport { load } from \"cheerio\";\nimport type { SrcSetDefinition } from \"srcset\";\nimport { parseSrcset, stringifySrcset } from \"srcset\";\nimport { isHeaderBlacklisted } from \"./headerBlacklist.js\";\nimport { logDebug } from \"./log.js\";\n\n// TODO cheerio does not have Element type, so we define it here\ninterface Element {\n attribs: {\n [key: string]: string;\n };\n}\n\n/**\n * Load HTML from origin and perform transformation of URLs to absolute\n * @param domain Domain of the origin cloudfront\n * @param path Path of the file we want to retrieve\n * @returns Response object\n */\nexport function loadOriginPage(domain: string, path: string) {\n return new Promise<CloudFrontResponse>((resolve, reject) => {\n logDebug(`Pulling page from ${domain}${path}`);\n let responseBody = \"\";\n const req = get(\n {\n hostname: domain,\n port: 443,\n path: path\n },\n res => {\n res.on(\"data\", chunk => (responseBody += chunk));\n res.on(\"end\", () => {\n logDebug(`Parsing page`);\n const html = parseHtml(responseBody, domain);\n const response: CloudFrontResponse = {\n body: html,\n status: \"200\",\n statusDescription: \"ok\",\n headers: {}\n };\n\n // Rewrite headers from the HTTP response\n for (const header of Object.keys(res.headers)) {\n // We cannot set any header we want.\n // CloudFront is restricting us from setting or changing some headers.\n if (isHeaderBlacklisted(header)) {\n continue;\n }\n\n const value = res.headers[header];\n if (Array.isArray(value)) {\n response.headers[header] = value.map(h => ({\n key: header,\n value: h\n }));\n } else if (value) {\n response.headers[header] = [\n {\n key: header,\n value: value\n }\n ];\n }\n }\n\n logDebug(`Page parsed`);\n resolve(response);\n });\n }\n );\n\n req.on(\"error\", e => {\n reject({\n statusCode: 500,\n body: e.message\n });\n });\n });\n}\n\nfunction parseHtml(html: string, domain: string) {\n const doc = load(html);\n const host = `https://${domain}`;\n\n doc(\"head > link\").each((_i, el) => {\n prefixUrl(el, \"href\", host);\n });\n\n doc(\"script\").each((_i, el) => {\n prefixUrl(el, \"src\", host);\n });\n\n doc(\"body\")\n .find(\"img\")\n .each((_i, el) => {\n prefixUrl(el, \"src\", host);\n\n // Handle also srcset property for responsive images.\n const srcset = el.attribs[\"srcset\"];\n if (srcset) {\n const srcsetParsed = parseSrcset(srcset);\n const srcsetRebased = srcsetParsed.map<SrcSetDefinition>(src => {\n if (src.url.startsWith(\"/\")) {\n return {\n url: host + src.url,\n density: src.density,\n width: src.width\n };\n }\n\n return src;\n });\n\n el.attribs[\"srcset\"] = stringifySrcset(srcsetRebased);\n }\n });\n\n return doc.html();\n}\n\nfunction prefixUrl(el: Element, attr: string, host: string) {\n const href = el.attribs[attr];\n if (href && href.startsWith(\"/\")) {\n el.attribs[attr] = host + href;\n }\n}\n"],"names":["loadOriginPage","domain","path","Promise","resolve","reject","logDebug","responseBody","req","get","res","chunk","html","parseHtml","response","header","Object","isHeaderBlacklisted","value","Array","h","e","doc","load","host","_i","el","prefixUrl","srcset","srcsetParsed","parseSrcset","srcsetRebased","src","stringifySrcset","attr","href"],"mappings":";;;;;AAqBO,SAASA,eAAeC,MAAc,EAAEC,IAAY;IACvD,OAAO,IAAIC,QAA4B,CAACC,SAASC;QAC7CC,SAAS,CAAC,kBAAkB,EAAEL,SAASC,MAAM;QAC7C,IAAIK,eAAe;QACnB,MAAMC,MAAMC,IACR;YACI,UAAUR;YACV,MAAM;YACN,MAAMC;QACV,GACAQ,CAAAA;YACIA,IAAI,EAAE,CAAC,QAAQC,CAAAA,QAAUJ,gBAAgBI;YACzCD,IAAI,EAAE,CAAC,OAAO;gBACVJ,SAAS;gBACT,MAAMM,OAAOC,UAAUN,cAAcN;gBACrC,MAAMa,WAA+B;oBACjC,MAAMF;oBACN,QAAQ;oBACR,mBAAmB;oBACnB,SAAS,CAAC;gBACd;gBAGA,KAAK,MAAMG,UAAUC,OAAO,IAAI,CAACN,IAAI,OAAO,EAAG;oBAG3C,IAAIO,oBAAoBF,SACpB;oBAGJ,MAAMG,QAAQR,IAAI,OAAO,CAACK,OAAO;oBACjC,IAAII,MAAM,OAAO,CAACD,QACdJ,SAAS,OAAO,CAACC,OAAO,GAAGG,MAAM,GAAG,CAACE,CAAAA,IAAM;4BACvC,KAAKL;4BACL,OAAOK;wBACX;yBACG,IAAIF,OACPJ,SAAS,OAAO,CAACC,OAAO,GAAG;wBACvB;4BACI,KAAKA;4BACL,OAAOG;wBACX;qBACH;gBAET;gBAEAZ,SAAS;gBACTF,QAAQU;YACZ;QACJ;QAGJN,IAAI,EAAE,CAAC,SAASa,CAAAA;YACZhB,OAAO;gBACH,YAAY;gBACZ,MAAMgB,EAAE,OAAO;YACnB;QACJ;IACJ;AACJ;AAEA,SAASR,UAAUD,IAAY,EAAEX,MAAc;IAC3C,MAAMqB,MAAMC,KAAKX;IACjB,MAAMY,OAAO,CAAC,QAAQ,EAAEvB,QAAQ;IAEhCqB,IAAI,eAAe,IAAI,CAAC,CAACG,IAAIC;QACzBC,UAAUD,IAAI,QAAQF;IAC1B;IAEAF,IAAI,UAAU,IAAI,CAAC,CAACG,IAAIC;QACpBC,UAAUD,IAAI,OAAOF;IACzB;IAEAF,IAAI,QACC,IAAI,CAAC,OACL,IAAI,CAAC,CAACG,IAAIC;QACPC,UAAUD,IAAI,OAAOF;QAGrB,MAAMI,SAASF,GAAG,OAAO,CAAC,SAAS;QACnC,IAAIE,QAAQ;YACR,MAAMC,eAAeC,YAAYF;YACjC,MAAMG,gBAAgBF,aAAa,GAAG,CAAmBG,CAAAA;gBACrD,IAAIA,IAAI,GAAG,CAAC,UAAU,CAAC,MACnB,OAAO;oBACH,KAAKR,OAAOQ,IAAI,GAAG;oBACnB,SAASA,IAAI,OAAO;oBACpB,OAAOA,IAAI,KAAK;gBACpB;gBAGJ,OAAOA;YACX;YAEAN,GAAG,OAAO,CAAC,SAAS,GAAGO,gBAAgBF;QAC3C;IACJ;IAEJ,OAAOT,IAAI,IAAI;AACnB;AAEA,SAASK,UAAUD,EAAW,EAAEQ,IAAY,EAAEV,IAAY;IACtD,MAAMW,OAAOT,GAAG,OAAO,CAACQ,KAAK;IAC7B,IAAIC,QAAQA,KAAK,UAAU,CAAC,MACxBT,GAAG,OAAO,CAACQ,KAAK,GAAGV,OAAOW;AAElC"}
@@ -0,0 +1,12 @@
1
+ import type { CloudFrontRequestEvent } from "../../lambdaEdge/index.js";
2
+ export interface VariantConfig {
3
+ domain: string;
4
+ weight: number;
5
+ }
6
+ export type GatewayConfig = Record<string, VariantConfig>;
7
+ /**
8
+ * Loads traffic splitting config.
9
+ * It will, however not call WCP directly, but serve it from a locally cached file,
10
+ * as explained here https://www.notion.so/webiny/How-traffic-config-is-cached-2c8db57ca2b547a2b2fb1adf378cd191
11
+ */
12
+ export declare function loadTrafficSplittingConfig(event: CloudFrontRequestEvent): Promise<GatewayConfig>;
@@ -0,0 +1,47 @@
1
+ import { get } from "https";
2
+ import { logDebug } from "./log.js";
3
+ const configPath = "/_config";
4
+ const configCache = new Map();
5
+ async function loadTrafficSplittingConfig(event) {
6
+ const domain = event.Records[0].cf.config.distributionDomainName;
7
+ let config = configCache.get(domain);
8
+ if (!config || isCacheExpired(config.timestamp)) {
9
+ logDebug("No config in cache");
10
+ config = {
11
+ config: await loadConfigCore(domain),
12
+ timestamp: Date.now()
13
+ };
14
+ configCache.set(domain, config);
15
+ }
16
+ return config.config;
17
+ }
18
+ function loadConfigCore(domain) {
19
+ return new Promise((resolve, reject)=>{
20
+ let dataString = "";
21
+ const req = get({
22
+ hostname: domain,
23
+ port: 443,
24
+ path: configPath
25
+ }, function(res) {
26
+ res.on("data", (chunk)=>{
27
+ dataString += chunk;
28
+ });
29
+ res.on("end", ()=>{
30
+ resolve(JSON.parse(dataString));
31
+ });
32
+ });
33
+ req.on("error", (e)=>{
34
+ reject({
35
+ statusCode: 500,
36
+ body: e.message
37
+ });
38
+ });
39
+ });
40
+ }
41
+ function isCacheExpired(timestamp) {
42
+ const ttl = 60000;
43
+ return Date.now() - timestamp > ttl;
44
+ }
45
+ export { loadTrafficSplittingConfig };
46
+
47
+ //# sourceMappingURL=loadTrafficSplittingConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/utils/loadTrafficSplittingConfig.js","sources":["../../../src/stagedRollouts/utils/loadTrafficSplittingConfig.ts"],"sourcesContent":["import { get } from \"https\";\nimport type { CloudFrontRequestEvent } from \"~/lambdaEdge/index.js\";\nimport { logDebug } from \"./log.js\";\n\n// Config file has a fixed URL within CDN, so it can be properly cached.\n// This way we achieve better performance, because CDN does not have to call WCP API for config every time,\n// but it can use it's own cache for a lookup.\nconst configPath = \"/_config\";\n\n// Config is locally cached within live lambda for a short time (1 minute).\n// Config must be cached per domain.\n// Otherwise cache will spill over different apps, because we may share this lambda.\nconst configCache = new Map<string, GatewayConfigCache>();\n\ninterface GatewayConfigCache {\n config: GatewayConfig;\n timestamp: number;\n}\n\nexport interface VariantConfig {\n domain: string;\n weight: number;\n}\n\nexport type GatewayConfig = Record<string, VariantConfig>;\n\n/**\n * Loads traffic splitting config.\n * It will, however not call WCP directly, but serve it from a locally cached file,\n * as explained here https://www.notion.so/webiny/How-traffic-config-is-cached-2c8db57ca2b547a2b2fb1adf378cd191\n */\nexport async function loadTrafficSplittingConfig(event: CloudFrontRequestEvent) {\n // Retrieve domain of the CloudFront distribution.\n // We need it to make sure we cache config per application.\n // For example API and website could share the same lambda instance.\n // So we cache it separately for each domain (each CloudFront).\n const domain = event.Records[0].cf.config.distributionDomainName;\n\n let config = configCache.get(domain);\n if (!config || isCacheExpired(config.timestamp)) {\n logDebug(\"No config in cache\");\n config = {\n config: await loadConfigCore(domain),\n timestamp: Date.now()\n };\n\n configCache.set(domain, config);\n }\n\n return config.config;\n}\n\nfunction loadConfigCore(domain: string) {\n return new Promise<GatewayConfig>((resolve, reject) => {\n let dataString = \"\";\n\n const req = get(\n {\n hostname: domain,\n port: 443,\n path: configPath\n },\n function (res) {\n res.on(\"data\", chunk => {\n dataString += chunk;\n });\n res.on(\"end\", () => {\n resolve(JSON.parse(dataString));\n });\n }\n );\n\n req.on(\"error\", e => {\n reject({\n statusCode: 500,\n body: e.message\n });\n });\n });\n}\n\nfunction isCacheExpired(timestamp: number) {\n const ttl = 60 * 1000; // 1 minute\n return Date.now() - timestamp > ttl;\n}\n"],"names":["configPath","configCache","Map","loadTrafficSplittingConfig","event","domain","config","isCacheExpired","logDebug","loadConfigCore","Date","Promise","resolve","reject","dataString","req","get","res","chunk","JSON","e","timestamp","ttl"],"mappings":";;AAOA,MAAMA,aAAa;AAKnB,MAAMC,cAAc,IAAIC;AAmBjB,eAAeC,2BAA2BC,KAA6B;IAK1E,MAAMC,SAASD,MAAM,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,sBAAsB;IAEhE,IAAIE,SAASL,YAAY,GAAG,CAACI;IAC7B,IAAI,CAACC,UAAUC,eAAeD,OAAO,SAAS,GAAG;QAC7CE,SAAS;QACTF,SAAS;YACL,QAAQ,MAAMG,eAAeJ;YAC7B,WAAWK,KAAK,GAAG;QACvB;QAEAT,YAAY,GAAG,CAACI,QAAQC;IAC5B;IAEA,OAAOA,OAAO,MAAM;AACxB;AAEA,SAASG,eAAeJ,MAAc;IAClC,OAAO,IAAIM,QAAuB,CAACC,SAASC;QACxC,IAAIC,aAAa;QAEjB,MAAMC,MAAMC,IACR;YACI,UAAUX;YACV,MAAM;YACN,MAAML;QACV,GACA,SAAUiB,GAAG;YACTA,IAAI,EAAE,CAAC,QAAQC,CAAAA;gBACXJ,cAAcI;YAClB;YACAD,IAAI,EAAE,CAAC,OAAO;gBACVL,QAAQO,KAAK,KAAK,CAACL;YACvB;QACJ;QAGJC,IAAI,EAAE,CAAC,SAASK,CAAAA;YACZP,OAAO;gBACH,YAAY;gBACZ,MAAMO,EAAE,OAAO;YACnB;QACJ;IACJ;AACJ;AAEA,SAASb,eAAec,SAAiB;IACrC,MAAMC,MAAM;IACZ,OAAOZ,KAAK,GAAG,KAAKW,YAAYC;AACpC"}
@@ -0,0 +1,4 @@
1
+ import type { CloudFrontRequestEvent } from "../../lambdaEdge/index.js";
2
+ export declare function loadVariantOrigin(event: CloudFrontRequestEvent): Promise<import("aws-lambda").CloudFrontRequest | import("aws-lambda").CloudFrontResultResponse | {
3
+ variant: import("../utils/loadTrafficSplittingConfig.js").VariantConfig;
4
+ }>;
@@ -0,0 +1,51 @@
1
+ import { getHeader, notFoundResponse } from "../../lambdaEdge/index.js";
2
+ import { variantFixedKey, variantRandomKey } from "./common.js";
3
+ import { loadTrafficSplittingConfig } from "./loadTrafficSplittingConfig.js";
4
+ import { logDebug } from "./log.js";
5
+ async function loadVariantOrigin(event) {
6
+ const cf = event.Records[0].cf;
7
+ const request = cf.request;
8
+ const config = await loadTrafficSplittingConfig(event);
9
+ const variantFixed = getHeader(request.headers, variantFixedKey);
10
+ if (variantFixed) {
11
+ const variantConfig = config[variantFixed];
12
+ if (variantConfig) return {
13
+ variant: variantConfig
14
+ };
15
+ return notFoundResponse(`No variant ${variantFixed} found`);
16
+ }
17
+ const variantRandom = Number(getHeader(request.headers, variantRandomKey));
18
+ if (isNaN(variantRandom)) {
19
+ logDebug("No random variant passed, passing the request");
20
+ return request;
21
+ }
22
+ logDebug(`Variant random ${variantRandom}`);
23
+ const variantConfig = getRandomVariant(config, variantRandom);
24
+ if (!variantConfig) {
25
+ logDebug("No variant is found");
26
+ return notFoundResponse("No variant is found");
27
+ }
28
+ return {
29
+ variant: variantConfig
30
+ };
31
+ }
32
+ function getRandomVariant(config, random) {
33
+ let totalWeight = 0;
34
+ const variants = Object.keys(config);
35
+ for (const variant of variants){
36
+ const variantConfig = config[variant];
37
+ if (variantConfig.weight) totalWeight += variantConfig.weight;
38
+ }
39
+ if (totalWeight <= 0 || random < 0) return;
40
+ random = random * totalWeight / 100;
41
+ for (const variant of variants){
42
+ const variantConfig = config[variant];
43
+ if (variantConfig.weight) if (random <= variantConfig.weight) {
44
+ logDebug(`Variant ${variant} selected`);
45
+ return config[variant];
46
+ } else random -= variantConfig.weight;
47
+ }
48
+ }
49
+ export { loadVariantOrigin };
50
+
51
+ //# sourceMappingURL=loadVariantOrigin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/utils/loadVariantOrigin.js","sources":["../../../src/stagedRollouts/utils/loadVariantOrigin.ts"],"sourcesContent":["import type { CloudFrontRequestEvent } from \"~/lambdaEdge/index.js\";\nimport { getHeader, notFoundResponse } from \"~/lambdaEdge/index.js\";\n\nimport { variantFixedKey, variantRandomKey } from \"../utils/common.js\";\nimport type { GatewayConfig } from \"../utils/loadTrafficSplittingConfig.js\";\nimport { loadTrafficSplittingConfig } from \"../utils/loadTrafficSplittingConfig.js\";\nimport { logDebug } from \"./log.js\";\n\nexport async function loadVariantOrigin(event: CloudFrontRequestEvent) {\n const cf = event.Records[0].cf;\n const request = cf.request;\n\n const config = await loadTrafficSplittingConfig(event);\n\n const variantFixed = getHeader(request.headers, variantFixedKey);\n if (variantFixed) {\n const variantConfig = config[variantFixed];\n if (variantConfig) {\n return { variant: variantConfig };\n } else {\n return notFoundResponse(`No variant ${variantFixed} found`);\n }\n }\n\n const variantRandom = Number(getHeader(request.headers, variantRandomKey));\n if (isNaN(variantRandom)) {\n logDebug(\"No random variant passed, passing the request\");\n // Random variant header should be always present.\n // It it's not, something bad happened, so we just pass request further.\n return request;\n }\n\n logDebug(`Variant random ${variantRandom}`);\n\n const variantConfig = getRandomVariant(config, variantRandom);\n if (!variantConfig) {\n // If no variant is matching the random value, just return 404.\n // This should happen only if there is really not a single variant serving traffic.\n logDebug(`No variant is found`);\n return notFoundResponse(`No variant is found`);\n }\n\n return { variant: variantConfig };\n}\n\nfunction getRandomVariant(config: GatewayConfig, random: number) {\n let totalWeight = 0;\n\n const variants = Object.keys(config);\n for (const variant of variants) {\n const variantConfig = config[variant];\n if (variantConfig.weight) {\n // do not count bad or negative weights\n totalWeight += variantConfig.weight;\n }\n }\n\n if (totalWeight <= 0 || random < 0) {\n return;\n }\n\n // Normalize random value to total weight of traffic splitting rates.\n random = (random * totalWeight) / 100;\n\n for (const variant of variants) {\n const variantConfig = config[variant];\n if (!variantConfig.weight) {\n continue;\n }\n\n if (random <= variantConfig.weight) {\n logDebug(`Variant ${variant} selected`);\n return config[variant];\n } else {\n random -= variantConfig.weight;\n }\n }\n\n return;\n}\n"],"names":["loadVariantOrigin","event","cf","request","config","loadTrafficSplittingConfig","variantFixed","getHeader","variantFixedKey","variantConfig","notFoundResponse","variantRandom","Number","variantRandomKey","isNaN","logDebug","getRandomVariant","random","totalWeight","variants","Object","variant"],"mappings":";;;;AAQO,eAAeA,kBAAkBC,KAA6B;IACjE,MAAMC,KAAKD,MAAM,OAAO,CAAC,EAAE,CAAC,EAAE;IAC9B,MAAME,UAAUD,GAAG,OAAO;IAE1B,MAAME,SAAS,MAAMC,2BAA2BJ;IAEhD,MAAMK,eAAeC,UAAUJ,QAAQ,OAAO,EAAEK;IAChD,IAAIF,cAAc;QACd,MAAMG,gBAAgBL,MAAM,CAACE,aAAa;QAC1C,IAAIG,eACA,OAAO;YAAE,SAASA;QAAc;QAEhC,OAAOC,iBAAiB,CAAC,WAAW,EAAEJ,aAAa,MAAM,CAAC;IAElE;IAEA,MAAMK,gBAAgBC,OAAOL,UAAUJ,QAAQ,OAAO,EAAEU;IACxD,IAAIC,MAAMH,gBAAgB;QACtBI,SAAS;QAGT,OAAOZ;IACX;IAEAY,SAAS,CAAC,eAAe,EAAEJ,eAAe;IAE1C,MAAMF,gBAAgBO,iBAAiBZ,QAAQO;IAC/C,IAAI,CAACF,eAAe;QAGhBM,SAAS;QACT,OAAOL,iBAAiB;IAC5B;IAEA,OAAO;QAAE,SAASD;IAAc;AACpC;AAEA,SAASO,iBAAiBZ,MAAqB,EAAEa,MAAc;IAC3D,IAAIC,cAAc;IAElB,MAAMC,WAAWC,OAAO,IAAI,CAAChB;IAC7B,KAAK,MAAMiB,WAAWF,SAAU;QAC5B,MAAMV,gBAAgBL,MAAM,CAACiB,QAAQ;QACrC,IAAIZ,cAAc,MAAM,EAEpBS,eAAeT,cAAc,MAAM;IAE3C;IAEA,IAAIS,eAAe,KAAKD,SAAS,GAC7B;IAIJA,SAAUA,SAASC,cAAe;IAElC,KAAK,MAAMG,WAAWF,SAAU;QAC5B,MAAMV,gBAAgBL,MAAM,CAACiB,QAAQ;QACrC,IAAKZ,cAAc,MAAM,EAIzB,IAAIQ,UAAUR,cAAc,MAAM,EAAE;YAChCM,SAAS,CAAC,QAAQ,EAAEM,QAAQ,SAAS,CAAC;YACtC,OAAOjB,MAAM,CAACiB,QAAQ;QAC1B,OACIJ,UAAUR,cAAc,MAAM;IAEtC;AAGJ"}
@@ -0,0 +1 @@
1
+ export declare function logDebug(...args: any[]): void;
@@ -0,0 +1,6 @@
1
+ function logDebug(...args) {
2
+ if ("true" === process.env.DEBUG) console.log(...args);
3
+ }
4
+ export { logDebug };
5
+
6
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stagedRollouts/utils/log.js","sources":["../../../src/stagedRollouts/utils/log.ts"],"sourcesContent":["export function logDebug(...args: any[]) {\n // If DEBUG variable is not set during build,\n // this function should be minified to an empty one and removed completely from the bundle.\n if (process.env.DEBUG === \"true\") {\n console.log(...args);\n }\n}\n"],"names":["logDebug","args","process","console"],"mappings":"AAAO,SAASA,SAAS,GAAGC,IAAW;IAGnC,IAAIC,AAAsB,WAAtBA,QAAQ,GAAG,CAAC,KAAK,EACjBC,QAAQ,GAAG,IAAIF;AAEvB"}