@lighthouse/common 6.1.0-canary.8 → 6.2.0-canary.1

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.
@@ -13,27 +13,17 @@ function buildFetchUrl(url, options) {
13
13
  height,
14
14
  width,
15
15
  quality,
16
- shouldUseCloudfront,
17
- Policy,
18
- KeyPairId,
19
- Signature
16
+ shouldUseCloudfront
20
17
  } = options;
21
18
  if (shouldUseCloudfront) {
22
- const isWebContext = shouldUseCloudfront && typeof window === 'object';
23
- const paramMap = {
24
- width,
25
- height,
26
- quality,
27
- fit: 'contain'
28
- };
29
- if (isWebContext) {
30
- paramMap.Policy = Policy;
31
- paramMap['Key-Pair-Id'] = KeyPairId;
32
- paramMap.Signature = Signature;
33
- }
34
- const params = Object.entries(paramMap).filter(([, value]) => value != null).map(([key, value]) => `${key}=${value.toString()}`);
35
- const paramsString = params.join('&');
36
- return `${cloudfrontBaseUrl}/${url}?${paramsString}`;
19
+ const transformations = [];
20
+ if (width) transformations.push(`width=${width.toString()}`);
21
+ if (height) transformations.push(`height=${height.toString()}`);
22
+ if (quality) transformations.push(`quality=${quality.toString()}`);
23
+ transformations.push(`fit=contain`);
24
+ const transformationsString = transformations.join('&');
25
+ const fetchUrl = `${cloudfrontBaseUrl}/${url}?${transformationsString}`;
26
+ return fetchUrl;
37
27
  }
38
28
  const transformations = [];
39
29
  let transformationsString = '';
@@ -27,6 +27,11 @@ const fetchImageForPdfGeneratorService = async function (url) {
27
27
  if (!applicationId) {
28
28
  throw new Error('Requestor has insufficient permissions');
29
29
  }
30
+ const nextUrl = new URL(`http://s3.amazon.com/${url}`);
31
+ const urlSearchParams = nextUrl.searchParams;
32
+ console.log({
33
+ urlSearchParams
34
+ });
30
35
  const keyWithTransformations = url.substring(url.indexOf(applicationId));
31
36
  const alreadyTransformedImage = await fetchResourceFromS3({
32
37
  bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,
@@ -39,8 +44,7 @@ const fetchImageForPdfGeneratorService = async function (url) {
39
44
  });
40
45
  return fullDataUrl;
41
46
  }
42
- const keyWithoutTransformations = `/${keyWithTransformations.split('?')[0]}`;
43
- const transformerResponse = await requestImageTransformation(keyWithoutTransformations);
47
+ const transformerResponse = await requestImageTransformation(keyWithTransformations);
44
48
  const statusCode = transformerResponse.statusCode;
45
49
  switch (statusCode) {
46
50
  case 200:
@@ -6,6 +6,12 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.fetchImageForWeb = void 0;
7
7
  var _images = require("../../images");
8
8
  var _fetchLighthouseLogo = require("../fetch-lighthouse-logo");
9
+ var _fetchImage = require("../fetch-image");
10
+ var _imageValidators = require("../image-validators");
11
+ const contentTypes = {
12
+ 'image/png': 'png',
13
+ 'image/jpeg': 'jpeg'
14
+ };
9
15
  const fetchImageForWeb = async function (url, options) {
10
16
  const {
11
17
  isHeader = false,
@@ -15,18 +21,26 @@ const fetchImageForWeb = async function (url, options) {
15
21
  } = options;
16
22
  try {
17
23
  const firstParamConnector = url.indexOf('?') > -1 ? '&' : '?';
18
- const hasSignatureParams = url.includes('Signature=') && url.includes('Policy=') && url.includes('Key-Pair-Id=');
19
- const constructedUrl = !hasSignatureParams ? `${url}${firstParamConnector}Signature=${Signature}&Policy=${Policy}&Key-Pair-Id=${KeyPairId}` : url;
24
+ const urlToEncode = `${url}${firstParamConnector}Signature=${Signature}&Policy=${Policy}&Key-Pair-Id=${KeyPairId}`;
25
+ const encodedUrl = encodeURI(urlToEncode);
20
26
  console.debug('Fetching image via CloudFront For Web');
21
- const imageResponse = await fetch(constructedUrl);
27
+ const imageResponse = await fetch(encodedUrl);
22
28
  const contentLengthHeader = imageResponse.headers.get('content-length');
29
+ const contentType = imageResponse.headers.get('content-type');
23
30
  if (contentLengthHeader === '0') {
24
31
  return Promise.reject(new Error(`Failed to fetch image as no content length: ${encodedUrl}`));
25
32
  }
26
33
  if (!imageResponse.ok) {
27
34
  return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`));
28
35
  }
29
- return await imageResponse.arrayBuffer();
36
+ const imageType = contentTypes[contentType];
37
+ const logoArrayBuffer = await imageResponse.arrayBuffer();
38
+ const base64Flag = `data:image/${imageType};base64,`;
39
+ const imageStr = (0, _fetchImage.arrayBufferToBase64)(logoArrayBuffer);
40
+ const base64 = `${base64Flag}${imageStr}`;
41
+ const isValid = (0, _imageValidators.validateBase64Image)(base64);
42
+ if (!isValid) throw new Error('InvalidImageError');
43
+ return base64;
30
44
  } catch (error) {
31
45
  if (isHeader) {
32
46
  // NOTE: Replace failed headers with LH logo
@@ -12,9 +12,6 @@ function getAuditItemsData(items, data) {
12
12
  awsS3BaseUrl,
13
13
  cloudinaryBaseUrl,
14
14
  cloudfrontBaseUrl,
15
- Policy,
16
- KeyPairId,
17
- Signature,
18
15
  shouldUseCloudfront
19
16
  } = {},
20
17
  entity: {
@@ -58,28 +55,20 @@ function getAuditItemsData(items, data) {
58
55
  awsS3BaseUrl,
59
56
  cloudfrontBaseUrl,
60
57
  cloudinaryBaseUrl,
58
+ shouldUseCloudfront,
59
+ fit: true,
61
60
  height: 400,
62
61
  width: 600,
63
- quality: 50,
64
- fit: true,
65
- shouldUseCloudfront,
66
- Policy,
67
- KeyPairId,
68
- Signature
62
+ quality: 50
69
63
  });
70
- const link = shouldUseCloudfront ? `${cloudfrontBaseUrl}/${item.signedAssets[assetIndex]}` : `${awsS3BaseUrl}/${asset}`;
64
+ const link = `${awsS3BaseUrl}/${asset}`;
71
65
  const thumbnailUrl = (0, _.buildFetchUrl)(asset, {
72
66
  awsS3BaseUrl,
73
67
  cloudfrontBaseUrl,
74
68
  cloudinaryBaseUrl,
75
69
  shouldUseCloudfront,
76
70
  width: 100,
77
- quality: 50,
78
- fit: true,
79
- shouldUseCloudfront,
80
- Policy,
81
- KeyPairId,
82
- Signature
71
+ quality: 50
83
72
  });
84
73
  const key = `${groupIndex}-item-asset-${assetIndex}`;
85
74
  return {
@@ -196,7 +196,7 @@ function generateContent(data) {
196
196
  timezone
197
197
  });
198
198
  const promises = {
199
- entry: (0, _helpers.buildAuditContent)(groupedData.items, data.settings),
199
+ entry: (0, _helpers.buildAuditContent)(groupedData.items),
200
200
  footerTemplate: (0, _helpers.buildTemplateContent)(footerFields.formGroups, data),
201
201
  headerTemplate: (0, _helpers.buildTemplateContent)(headerFields.formGroups, data)
202
202
  };
@@ -1,5 +1,3 @@
1
- import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
2
- import _typeof from "@babel/runtime/helpers/typeof";
3
1
  export function buildFetchUrl(url, options) {
4
2
  var awsS3BaseUrl = options.awsS3BaseUrl,
5
3
  _options$cloudfrontBa = options.cloudfrontBaseUrl,
@@ -9,35 +7,16 @@ export function buildFetchUrl(url, options) {
9
7
  height = options.height,
10
8
  width = options.width,
11
9
  quality = options.quality,
12
- shouldUseCloudfront = options.shouldUseCloudfront,
13
- Policy = options.Policy,
14
- KeyPairId = options.KeyPairId,
15
- Signature = options.Signature;
10
+ shouldUseCloudfront = options.shouldUseCloudfront;
16
11
  if (shouldUseCloudfront) {
17
- var isWebContext = shouldUseCloudfront && (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object';
18
- var paramMap = {
19
- width: width,
20
- height: height,
21
- quality: quality,
22
- fit: 'contain'
23
- };
24
- if (isWebContext) {
25
- paramMap.Policy = Policy;
26
- paramMap['Key-Pair-Id'] = KeyPairId;
27
- paramMap.Signature = Signature;
28
- }
29
- var params = Object.entries(paramMap).filter(function (_ref) {
30
- var _ref2 = _slicedToArray(_ref, 2),
31
- value = _ref2[1];
32
- return value != null;
33
- }).map(function (_ref3) {
34
- var _ref4 = _slicedToArray(_ref3, 2),
35
- key = _ref4[0],
36
- value = _ref4[1];
37
- return "".concat(key, "=").concat(value.toString());
38
- });
39
- var paramsString = params.join('&');
40
- return "".concat(cloudfrontBaseUrl, "/").concat(url, "?").concat(paramsString);
12
+ var _transformations = [];
13
+ if (width) _transformations.push("width=".concat(width.toString()));
14
+ if (height) _transformations.push("height=".concat(height.toString()));
15
+ if (quality) _transformations.push("quality=".concat(quality.toString()));
16
+ _transformations.push("fit=contain");
17
+ var _transformationsString = _transformations.join('&');
18
+ var _fetchUrl = "".concat(cloudfrontBaseUrl, "/").concat(url, "?").concat(_transformationsString);
19
+ return _fetchUrl;
41
20
  }
42
21
  var transformations = [];
43
22
  var transformationsString = '';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["buildFetchUrl","url","options","awsS3BaseUrl","_options$cloudfrontBa","cloudfrontBaseUrl","cloudinaryBaseUrl","fit","height","width","quality","shouldUseCloudfront","Policy","KeyPairId","Signature","isWebContext","window","_typeof","paramMap","params","Object","entries","filter","_ref","_ref2","_slicedToArray","value","map","_ref3","_ref4","key","concat","toString","paramsString","join","transformations","transformationsString","push","fetchUrl"],"sources":["../../../src/helpers/build-fetch-url/index.js"],"sourcesContent":["export function buildFetchUrl(url, options) {\n const {\n awsS3BaseUrl,\n cloudfrontBaseUrl = '',\n cloudinaryBaseUrl,\n fit,\n height,\n width,\n quality,\n shouldUseCloudfront,\n Policy,\n KeyPairId,\n Signature,\n } = options\n\n if (shouldUseCloudfront) {\n const isWebContext = shouldUseCloudfront && typeof window === 'object'\n\n const paramMap = {\n width,\n height,\n quality,\n fit: 'contain',\n }\n\n if (isWebContext) {\n paramMap.Policy = Policy\n paramMap['Key-Pair-Id'] = KeyPairId\n paramMap.Signature = Signature\n }\n const params = Object.entries(paramMap)\n .filter(([, value]) => value != null)\n .map(([key, value]) => `${key}=${value.toString()}`)\n\n const paramsString = params.join('&')\n return `${cloudfrontBaseUrl}/${url}?${paramsString}`\n }\n\n const transformations = []\n let transformationsString = ''\n\n if (width) transformations.push(`w_${width.toString()}`)\n if (height) transformations.push(`h_${height.toString()}`)\n if (quality) transformations.push(`q_${quality.toString()}`)\n if (fit) transformations.push('c_fit')\n\n transformationsString = `${transformations.join(',')}/`\n\n const fetchUrl = `${cloudinaryBaseUrl}/${transformationsString}${awsS3BaseUrl}/${url}`\n\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AAA;MAAA,IAAAC,KAAA,GAAAJ,cAAA,CAAAG,KAAA;QAAEE,GAAG,GAAAD,KAAA;QAAEH,KAAK,GAAAG,KAAA;MAAA,UAAAE,MAAA,CAASD,GAAG,OAAAC,MAAA,CAAIL,KAAK,CAACM,QAAQ,CAAC,CAAC;IAAA,CAAE,CAAC;IAEtD,IAAMC,YAAY,GAAGd,MAAM,CAACe,IAAI,CAAC,GAAG,CAAC;IACrC,UAAAH,MAAA,CAAU1B,iBAAiB,OAAA0B,MAAA,CAAI9B,GAAG,OAAA8B,MAAA,CAAIE,YAAY;EACpD;EAEA,IAAME,eAAe,GAAG,EAAE;EAC1B,IAAIC,qBAAqB,GAAG,EAAE;EAE9B,IAAI3B,KAAK,EAAE0B,eAAe,CAACE,IAAI,MAAAN,MAAA,CAAMtB,KAAK,CAACuB,QAAQ,CAAC,CAAC,CAAE,CAAC;EACxD,IAAIxB,MAAM,EAAE2B,eAAe,CAACE,IAAI,MAAAN,MAAA,CAAMvB,MAAM,CAACwB,QAAQ,CAAC,CAAC,CAAE,CAAC;EAC1D,IAAItB,OAAO,EAAEyB,eAAe,CAACE,IAAI,MAAAN,MAAA,CAAMrB,OAAO,CAACsB,QAAQ,CAAC,CAAC,CAAE,CAAC;EAC5D,IAAIzB,GAAG,EAAE4B,eAAe,CAACE,IAAI,CAAC,OAAO,CAAC;EAEtCD,qBAAqB,MAAAL,MAAA,CAAMI,eAAe,CAACD,IAAI,CAAC,GAAG,CAAC,MAAG;EAEvD,IAAMI,QAAQ,MAAAP,MAAA,CAAMzB,iBAAiB,OAAAyB,MAAA,CAAIK,qBAAqB,EAAAL,MAAA,CAAG5B,YAAY,OAAA4B,MAAA,CAAI9B,GAAG,CAAE;EAEtF,OAAOqC,QAAQ;AACjB","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["buildFetchUrl","url","options","awsS3BaseUrl","_options$cloudfrontBa","cloudfrontBaseUrl","cloudinaryBaseUrl","fit","height","width","quality","shouldUseCloudfront","transformations","push","concat","toString","transformationsString","join","fetchUrl"],"sources":["../../../src/helpers/build-fetch-url/index.js"],"sourcesContent":["export function buildFetchUrl(url, options) {\n const {\n awsS3BaseUrl,\n cloudfrontBaseUrl = '',\n cloudinaryBaseUrl,\n fit,\n height,\n width,\n quality,\n shouldUseCloudfront,\n } = options\n\n if (shouldUseCloudfront) {\n const transformations = []\n\n if (width) transformations.push(`width=${width.toString()}`)\n if (height) transformations.push(`height=${height.toString()}`)\n if (quality) transformations.push(`quality=${quality.toString()}`)\n transformations.push(`fit=contain`)\n\n const transformationsString = transformations.join('&')\n\n const fetchUrl = `${cloudfrontBaseUrl}/${url}?${transformationsString}`\n return fetchUrl\n }\n\n const transformations = []\n let transformationsString = ''\n\n if (width) transformations.push(`w_${width.toString()}`)\n if (height) transformations.push(`h_${height.toString()}`)\n if (quality) transformations.push(`q_${quality.toString()}`)\n if (fit) transformations.push('c_fit')\n\n transformationsString = `${transformations.join(',')}/`\n\n const fetchUrl = `${cloudinaryBaseUrl}/${transformationsString}${awsS3BaseUrl}/${url}`\n\n return fetchUrl\n}\n"],"mappings":"AAAA,OAAO,SAASA,aAAaA,CAACC,GAAG,EAAEC,OAAO,EAAE;EAC1C,IACEC,YAAY,GAQVD,OAAO,CARTC,YAAY;IAAAC,qBAAA,GAQVF,OAAO,CAPTG,iBAAiB;IAAjBA,iBAAiB,GAAAD,qBAAA,cAAG,EAAE,GAAAA,qBAAA;IACtBE,iBAAiB,GAMfJ,OAAO,CANTI,iBAAiB;IACjBC,GAAG,GAKDL,OAAO,CALTK,GAAG;IACHC,MAAM,GAIJN,OAAO,CAJTM,MAAM;IACNC,KAAK,GAGHP,OAAO,CAHTO,KAAK;IACLC,OAAO,GAELR,OAAO,CAFTQ,OAAO;IACPC,mBAAmB,GACjBT,OAAO,CADTS,mBAAmB;EAGrB,IAAIA,mBAAmB,EAAE;IACvB,IAAMC,gBAAe,GAAG,EAAE;IAE1B,IAAIH,KAAK,EAAEG,gBAAe,CAACC,IAAI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;AACjB","ignoreList":[]}
@@ -11,7 +11,7 @@ var s3 = new AWS.S3({
11
11
  });
12
12
  export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
13
13
  var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(url) {
14
- var urlMatch, applicationId, keyWithTransformations, alreadyTransformedImage, fullDataUrl, keyWithoutTransformations, transformerResponse, statusCode, _fullDataUrl, _transformerResponse$, redirectLocation, newlyTransformedImage, _fullDataUrl2, _t;
14
+ var urlMatch, applicationId, nextUrl, urlSearchParams, keyWithTransformations, alreadyTransformedImage, fullDataUrl, transformerResponse, statusCode, _fullDataUrl, _transformerResponse$, redirectLocation, newlyTransformedImage, _fullDataUrl2, _t;
15
15
  return _regeneratorRuntime.wrap(function (_context) {
16
16
  while (1) switch (_context.prev = _context.next) {
17
17
  case 0:
@@ -30,6 +30,11 @@ export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
30
30
  }
31
31
  throw new Error('Requestor has insufficient permissions');
32
32
  case 2:
33
+ nextUrl = new URL("http://s3.amazon.com/".concat(url));
34
+ urlSearchParams = nextUrl.searchParams;
35
+ console.log({
36
+ urlSearchParams: urlSearchParams
37
+ });
33
38
  keyWithTransformations = url.substring(url.indexOf(applicationId));
34
39
  _context.next = 3;
35
40
  return fetchResourceFromS3({
@@ -48,9 +53,8 @@ export var fetchImageForPdfGeneratorService = /*#__PURE__*/function () {
48
53
  });
49
54
  return _context.abrupt("return", fullDataUrl);
50
55
  case 4:
51
- keyWithoutTransformations = "/".concat(keyWithTransformations.split('?')[0]);
52
56
  _context.next = 5;
53
- return requestImageTransformation(keyWithoutTransformations);
57
+ return requestImageTransformation(keyWithTransformations);
54
58
  case 5:
55
59
  transformerResponse = _context.sent;
56
60
  statusCode = transformerResponse.statusCode;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["validateBase64Image","AWS","REGION","process","env","AWS_REGION","lambda","Lambda","region","s3","S3","fetchImageForPdfGeneratorService","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","urlMatch","applicationId","keyWithTransformations","alreadyTransformedImage","fullDataUrl","keyWithoutTransformations","transformerResponse","statusCode","_fullDataUrl","_transformerResponse$","redirectLocation","newlyTransformedImage","_fullDataUrl2","_t","wrap","_context","prev","next","console","debug","Error","match","substring","indexOf","fetchResourceFromS3","bucketName","concat","S3_BUCKET_IMAGE_TRANSFORMER_CACHE","key","sent","body","formatBase64Image","base64String","toString","abrupt","split","requestImageTransformation","headers","Location","stop","_x","apply","arguments","_x2","_requestImageTransformation","_callee2","lambdaEvent","params","result","response","errorMessage","_t2","_context2","requestContext","http","method","path","FunctionName","IMAGE_TRANSFORMER_ARN","InvocationType","Payload","JSON","stringify","invoke","promise","parse","message","error","_x3","_fetchResourceFromS","_callee3","_ref2","_t3","_context3","Bucket","Key","getObject","Body","contentType","ContentType","contentLength","ContentLength","lastModified","LastModified","etag","ETag","code","_ref3","imageType","toLowerCase","includes","base64Flag","isValid"],"sources":["../../../src/helpers/fetch-image-for-pdf-generator-service/index.js"],"sourcesContent":["import { validateBase64Image } from '../image-validators'\nimport AWS from 'aws-sdk'\nconst REGION = process.env.AWS_REGION\n\nconst lambda = new AWS.Lambda({\n region: REGION,\n})\nconst s3 = new AWS.S3({\n region: REGION,\n})\n\nexport const fetchImageForPdfGeneratorService = async function(url) {\n console.debug(\n 'Fetching image via CloudFront For Serverless Pdf Generator Service'\n )\n\n if (!url) {\n throw new Error('URL is required to fetch image for PDF generator service')\n }\n\n const urlMatch = url && url.match(/([a-f0-9]{24})\\//)\n const applicationId = urlMatch && urlMatch[1]\n\n if (!applicationId) {\n throw new Error('Requestor has insufficient permissions')\n }\n\n const keyWithTransformations = url.substring(url.indexOf(applicationId))\n\n const alreadyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: keyWithTransformations,\n })\n\n if (alreadyTransformedImage?.body) {\n const fullDataUrl = formatBase64Image({\n base64String: alreadyTransformedImage.body.toString('base64'),\n key: keyWithTransformations,\n })\n return fullDataUrl\n }\n\n const keyWithoutTransformations = `/${keyWithTransformations.split('?')[0]}`\n\n const transformerResponse = await requestImageTransformation(\n keyWithoutTransformations\n )\n\n const statusCode = transformerResponse.statusCode\n\n switch (statusCode) {\n case 200: {\n console.debug('Image transformation successful')\n\n const fullDataUrl = formatBase64Image({\n base64String: transformerResponse.body.toString('base64'),\n key: keyWithTransformations,\n })\n\n return fullDataUrl\n }\n case 302: {\n console.debug(\n 'Image transformation successful but image is too big for lambda delivery, fetching directly from S3'\n )\n const redirectLocation = transformerResponse.headers?.Location\n if (redirectLocation) {\n const newlyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: keyWithTransformations,\n })\n console.debug(\n 'Image successfully fetched from S3 at:',\n redirectLocation\n )\n\n const fullDataUrl = formatBase64Image({\n base64String: newlyTransformedImage.body.toString('base64'),\n key: keyWithTransformations,\n })\n\n return fullDataUrl\n }\n throw new Error('Redirect response received but no location provided')\n }\n case 400:\n throw new Error(\n `Bad request to image transformer: ${transformerResponse.body}`\n )\n case 403:\n throw new Error('Requested transformed image is too big')\n case 404:\n throw new Error('The requested image does not exist')\n case 500:\n throw new Error(\n `Image transformation failed: ${transformerResponse.body}`\n )\n default:\n throw new Error(\n `Unexpected response from image transformer: ${statusCode} - ${transformerResponse.body}`\n )\n }\n}\n\nexport async function requestImageTransformation(key) {\n if (!key) {\n throw new Error('Image Path is required for image transformation')\n }\n\n console.debug(\n 'ImageTransformation: Invoking image transformer lambda for path:',\n key\n )\n\n const lambdaEvent = {\n requestContext: {\n http: {\n method: 'GET',\n path: key,\n },\n },\n }\n\n const params = {\n FunctionName: process.env.IMAGE_TRANSFORMER_ARN,\n InvocationType: 'RequestResponse',\n Payload: JSON.stringify(lambdaEvent),\n }\n\n try {\n const result = await lambda.invoke(params).promise()\n\n const response = JSON.parse(result.Payload)\n\n return response\n } catch (error) {\n const errorMessage = `Failed to invoke image transformer lambda: ${error.message}`\n console.error(errorMessage, error)\n throw new Error(errorMessage)\n }\n}\n\nexport async function fetchResourceFromS3({ bucketName, key }) {\n console.debug(\n `Fetching resource from S3 Bucket: '${bucketName}' at path: '${key}'`\n )\n if (!bucketName || !key) {\n throw new Error(\n 'bucketName and key are required for S3 resource fetch ' +\n JSON.stringify({ bucketName, key })\n )\n }\n\n const params = {\n Bucket: bucketName,\n Key: key,\n }\n\n try {\n const result = await s3.getObject(params).promise()\n\n return {\n body: result.Body,\n contentType: result.ContentType,\n contentLength: result.ContentLength,\n lastModified: result.LastModified,\n etag: result.ETag,\n }\n } catch (error) {\n if (error.code !== 'NoSuchKey') {\n console.error('Failed to fetch image:', error)\n throw new Error(`Failed to fetch image: ${bucketName}/${key}`)\n }\n\n console.debug('Image not found in transformed bucket, invoking transformer')\n }\n}\n\nexport function formatBase64Image({ base64String, key }) {\n if (!key) {\n throw new Error('Key is required for image formatting')\n }\n\n const imageType = key.toLowerCase().includes('.png') ? 'png' : 'jpeg'\n const base64Flag = `data:image/${imageType};base64,`\n const fullDataUrl = `${base64Flag}${base64String}`\n\n // Validate the formatted data URL\n const isValid = validateBase64Image(fullDataUrl)\n if (!isValid) {\n throw new Error('InvalidImageError')\n }\n\n return fullDataUrl\n}\n"],"mappings":";;AAAA,SAASA,mBAAmB,QAAQ,qBAAqB;AACzD,OAAOC,GAAG,MAAM,SAAS;AACzB,IAAMC,MAAM,GAAGC,OAAO,CAACC,GAAG,CAACC,UAAU;AAErC,IAAMC,MAAM,GAAG,IAAIL,GAAG,CAACM,MAAM,CAAC;EAC5BC,MAAM,EAAEN;AACV,CAAC,CAAC;AACF,IAAMO,EAAE,GAAG,IAAIR,GAAG,CAACS,EAAE,CAAC;EACpBF,MAAM,EAAEN;AACV,CAAC,CAAC;AAEF,OAAO,IAAMS,gCAAgC;EAAA,IAAAC,IAAA,GAAAC,iBAAA,cAAAC,mBAAA,CAAAC,IA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xE,KAAK,CAAC,mBAAmB,CAAC;EACtC;EAEA,OAAOhB,WAAW;AACpB","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["validateBase64Image","AWS","REGION","process","env","AWS_REGION","lambda","Lambda","region","s3","S3","fetchImageForPdfGeneratorService","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","urlMatch","applicationId","nextUrl","urlSearchParams","keyWithTransformations","alreadyTransformedImage","fullDataUrl","transformerResponse","statusCode","_fullDataUrl","_transformerResponse$","redirectLocation","newlyTransformedImage","_fullDataUrl2","_t","wrap","_context","prev","next","console","debug","Error","match","URL","concat","searchParams","log","substring","indexOf","fetchResourceFromS3","bucketName","S3_BUCKET_IMAGE_TRANSFORMER_CACHE","key","sent","body","formatBase64Image","base64String","toString","abrupt","requestImageTransformation","headers","Location","stop","_x","apply","arguments","_x2","_requestImageTransformation","_callee2","lambdaEvent","params","result","response","errorMessage","_t2","_context2","requestContext","http","method","path","FunctionName","IMAGE_TRANSFORMER_ARN","InvocationType","Payload","JSON","stringify","invoke","promise","parse","message","error","_x3","_fetchResourceFromS","_callee3","_ref2","_t3","_context3","Bucket","Key","getObject","Body","contentType","ContentType","contentLength","ContentLength","lastModified","LastModified","etag","ETag","code","_ref3","imageType","toLowerCase","includes","base64Flag","isValid"],"sources":["../../../src/helpers/fetch-image-for-pdf-generator-service/index.js"],"sourcesContent":["import { validateBase64Image } from '../image-validators'\nimport AWS from 'aws-sdk'\nconst REGION = process.env.AWS_REGION\n\nconst lambda = new AWS.Lambda({\n region: REGION,\n})\nconst s3 = new AWS.S3({\n region: REGION,\n})\n\nexport const fetchImageForPdfGeneratorService = async function (url) {\n console.debug(\n 'Fetching image via CloudFront For Serverless Pdf Generator Service'\n )\n\n if (!url) {\n throw new Error('URL is required to fetch image for PDF generator service')\n }\n\n const urlMatch = url && url.match(/([a-f0-9]{24})\\//)\n const applicationId = urlMatch && urlMatch[1]\n\n if (!applicationId) {\n throw new Error('Requestor has insufficient permissions')\n }\n\n const nextUrl = new URL(`http://s3.amazon.com/${url}`)\n\n const urlSearchParams = nextUrl.searchParams\n\n console.log({ urlSearchParams })\n\n const keyWithTransformations = url.substring(url.indexOf(applicationId))\n\n const alreadyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: keyWithTransformations,\n })\n\n if (alreadyTransformedImage?.body) {\n const fullDataUrl = formatBase64Image({\n base64String: alreadyTransformedImage.body.toString('base64'),\n key: keyWithTransformations,\n })\n return fullDataUrl\n }\n\n const transformerResponse = await requestImageTransformation(\n keyWithTransformations\n )\n\n const statusCode = transformerResponse.statusCode\n\n switch (statusCode) {\n case 200: {\n console.debug('Image transformation successful')\n\n const fullDataUrl = formatBase64Image({\n base64String: transformerResponse.body.toString('base64'),\n key: keyWithTransformations,\n })\n\n return fullDataUrl\n }\n case 302: {\n console.debug(\n 'Image transformation successful but image is too big for lambda delivery, fetching directly from S3'\n )\n const redirectLocation = transformerResponse.headers?.Location\n if (redirectLocation) {\n const newlyTransformedImage = await fetchResourceFromS3({\n bucketName: `${process.env.S3_BUCKET_IMAGE_TRANSFORMER_CACHE}`,\n key: keyWithTransformations,\n })\n console.debug(\n 'Image successfully fetched from S3 at:',\n redirectLocation\n )\n\n const fullDataUrl = formatBase64Image({\n base64String: newlyTransformedImage.body.toString('base64'),\n key: keyWithTransformations,\n })\n\n return fullDataUrl\n }\n throw new Error('Redirect response received but no location provided')\n }\n case 400:\n throw new Error(\n `Bad request to image transformer: ${transformerResponse.body}`\n )\n case 403:\n throw new Error('Requested transformed image is too big')\n case 404:\n throw new Error('The requested image does not exist')\n case 500:\n throw new Error(\n `Image transformation failed: ${transformerResponse.body}`\n )\n default:\n throw new Error(\n `Unexpected response from image transformer: ${statusCode} - ${transformerResponse.body}`\n )\n }\n}\n\nexport async function requestImageTransformation(key) {\n if (!key) {\n throw new Error('Image Path is required for image transformation')\n }\n\n console.debug(\n 'ImageTransformation: Invoking image transformer lambda for path:',\n key\n )\n\n const lambdaEvent = {\n requestContext: {\n http: {\n method: 'GET',\n path: key,\n },\n },\n }\n\n const params = {\n FunctionName: process.env.IMAGE_TRANSFORMER_ARN,\n InvocationType: 'RequestResponse',\n Payload: JSON.stringify(lambdaEvent),\n }\n\n try {\n const result = await lambda.invoke(params).promise()\n\n const response = JSON.parse(result.Payload)\n\n return response\n } catch (error) {\n const errorMessage = `Failed to invoke image transformer lambda: ${error.message}`\n console.error(errorMessage, error)\n throw new Error(errorMessage)\n }\n}\n\nexport async function fetchResourceFromS3({ bucketName, key }) {\n console.debug(\n `Fetching resource from S3 Bucket: '${bucketName}' at path: '${key}'`\n )\n if (!bucketName || !key) {\n throw new Error(\n 'bucketName and key are required for S3 resource fetch ' +\n JSON.stringify({ bucketName, key })\n )\n }\n\n const params = {\n Bucket: bucketName,\n Key: key,\n }\n\n try {\n const result = await s3.getObject(params).promise()\n\n return {\n body: result.Body,\n contentType: result.ContentType,\n contentLength: result.ContentLength,\n lastModified: result.LastModified,\n etag: result.ETag,\n }\n } catch (error) {\n if (error.code !== 'NoSuchKey') {\n console.error('Failed to fetch image:', error)\n throw new Error(`Failed to fetch image: ${bucketName}/${key}`)\n }\n\n console.debug('Image not found in transformed bucket, invoking transformer')\n }\n}\n\nexport function formatBase64Image({ base64String, key }) {\n if (!key) {\n throw new Error('Key is required for image formatting')\n }\n\n const imageType = key.toLowerCase().includes('.png') ? 'png' : 'jpeg'\n const base64Flag = `data:image/${imageType};base64,`\n const fullDataUrl = `${base64Flag}${base64String}`\n\n // Validate the formatted data URL\n const isValid = validateBase64Image(fullDataUrl)\n if (!isValid) {\n throw new Error('InvalidImageError')\n }\n\n return fullDataUrl\n}\n"],"mappings":";;AAAA,SAASA,mBAAmB,QAAQ,qBAAqB;AACzD,OAAOC,GAAG,MAAM,SAAS;AACzB,IAAMC,MAAM,GAAGC,OAAO,CAACC,GAAG,CAACC,UAAU;AAErC,IAAMC,MAAM,GAAG,IAAIL,GAAG,CAACM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AMsE,SAAS,GAAG3D,GAAG,CAAC4D,WAAW,CAAC,CAAC,CAACC,QAAQ,CAAC,MAAM,CAAC,GAAG,KAAK,GAAG,MAAM;EACrE,IAAMC,UAAU,iBAAAtE,MAAA,CAAiBmE,SAAS,aAAU;EACpD,IAAMrF,WAAW,MAAAkB,MAAA,CAAMsE,UAAU,EAAAtE,MAAA,CAAGY,YAAY,CAAE;;EAElD;EACA,IAAM2D,OAAO,GAAGjH,mBAAmB,CAACwB,WAAW,CAAC;EAChD,IAAI,CAACyF,OAAO,EAAE;IACZ,MAAM,IAAI1E,KAAK,CAAC,mBAAmB,CAAC;EACtC;EAEA,OAAOf,WAAW;AACpB","ignoreList":[]}
@@ -2,23 +2,30 @@ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
2
  import _regeneratorRuntime from "@babel/runtime/regenerator";
3
3
  import { imageNotFound } from '../../images';
4
4
  import { fetchLighthouseLogo } from '../fetch-lighthouse-logo';
5
+ import { arrayBufferToBase64 } from '../fetch-image';
6
+ import { validateBase64Image } from '../image-validators';
7
+ var contentTypes = {
8
+ 'image/png': 'png',
9
+ 'image/jpeg': 'jpeg'
10
+ };
5
11
  export var fetchImageForWeb = /*#__PURE__*/function () {
6
12
  var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(url, options) {
7
- var _options$isHeader, isHeader, Signature, Policy, KeyPairId, firstParamConnector, hasSignatureParams, constructedUrl, imageResponse, contentLengthHeader, _t;
13
+ var _options$isHeader, isHeader, Signature, Policy, KeyPairId, firstParamConnector, urlToEncode, encodedUrl, imageResponse, contentLengthHeader, contentType, imageType, logoArrayBuffer, base64Flag, imageStr, base64, isValid, _t;
8
14
  return _regeneratorRuntime.wrap(function (_context) {
9
15
  while (1) switch (_context.prev = _context.next) {
10
16
  case 0:
11
17
  _options$isHeader = options.isHeader, isHeader = _options$isHeader === void 0 ? false : _options$isHeader, Signature = options.Signature, Policy = options.Policy, KeyPairId = options.KeyPairId;
12
18
  _context.prev = 1;
13
19
  firstParamConnector = url.indexOf('?') > -1 ? '&' : '?';
14
- hasSignatureParams = url.includes('Signature=') && url.includes('Policy=') && url.includes('Key-Pair-Id=');
15
- constructedUrl = !hasSignatureParams ? "".concat(url).concat(firstParamConnector, "Signature=").concat(Signature, "&Policy=").concat(Policy, "&Key-Pair-Id=").concat(KeyPairId) : url;
20
+ urlToEncode = "".concat(url).concat(firstParamConnector, "Signature=").concat(Signature, "&Policy=").concat(Policy, "&Key-Pair-Id=").concat(KeyPairId);
21
+ encodedUrl = encodeURI(urlToEncode);
16
22
  console.debug('Fetching image via CloudFront For Web');
17
23
  _context.next = 2;
18
- return fetch(constructedUrl);
24
+ return fetch(encodedUrl);
19
25
  case 2:
20
26
  imageResponse = _context.sent;
21
27
  contentLengthHeader = imageResponse.headers.get('content-length');
28
+ contentType = imageResponse.headers.get('content-type');
22
29
  if (!(contentLengthHeader === '0')) {
23
30
  _context.next = 3;
24
31
  break;
@@ -31,28 +38,40 @@ export var fetchImageForWeb = /*#__PURE__*/function () {
31
38
  }
32
39
  return _context.abrupt("return", Promise.reject(new Error("Failed to fetch image: ".concat(encodedUrl))));
33
40
  case 4:
41
+ imageType = contentTypes[contentType];
34
42
  _context.next = 5;
35
43
  return imageResponse.arrayBuffer();
36
44
  case 5:
37
- return _context.abrupt("return", _context.sent);
45
+ logoArrayBuffer = _context.sent;
46
+ base64Flag = "data:image/".concat(imageType, ";base64,");
47
+ imageStr = arrayBufferToBase64(logoArrayBuffer);
48
+ base64 = "".concat(base64Flag).concat(imageStr);
49
+ isValid = validateBase64Image(base64);
50
+ if (isValid) {
51
+ _context.next = 6;
52
+ break;
53
+ }
54
+ throw new Error('InvalidImageError');
38
55
  case 6:
39
- _context.prev = 6;
56
+ return _context.abrupt("return", base64);
57
+ case 7:
58
+ _context.prev = 7;
40
59
  _t = _context["catch"](1);
41
60
  if (!isHeader) {
42
- _context.next = 7;
61
+ _context.next = 8;
43
62
  break;
44
63
  }
45
64
  // NOTE: Replace failed headers with LH logo
46
65
  console.error('FetchImageHeaderError', _t);
47
66
  return _context.abrupt("return", fetchLighthouseLogo());
48
- case 7:
67
+ case 8:
49
68
  console.error(_t);
50
69
  return _context.abrupt("return", imageNotFound);
51
- case 8:
70
+ case 9:
52
71
  case "end":
53
72
  return _context.stop();
54
73
  }
55
- }, _callee, null, [[1, 6]]);
74
+ }, _callee, null, [[1, 7]]);
56
75
  }));
57
76
  return function fetchImageForWeb(_x, _x2) {
58
77
  return _ref.apply(this, arguments);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["imageNotFound","fetchLighthouseLogo","fetchImageForWeb","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","options","_options$isHeader","isHeader","Signature","Policy","KeyPairId","firstParamConnector","hasSignatureParams","constructedUrl","imageResponse","contentLengthHeader","_t","wrap","_context","prev","next","indexOf","includes","concat","console","debug","fetch","sent","headers","get","abrupt","Promise","reject","Error","encodedUrl","ok","arrayBuffer","error","stop","_x","_x2","apply","arguments"],"sources":["../../../src/helpers/fetch-image-for-web/index.js"],"sourcesContent":["import { imageNotFound } from '../../images'\nimport { fetchLighthouseLogo } from '../fetch-lighthouse-logo'\nexport const fetchImageForWeb = async function (url, options) {\n const { isHeader = false, Signature, Policy, KeyPairId } = options\n\n \n try {\n const firstParamConnector = url.indexOf('?') > -1 ? '&' : '?'\n\n const hasSignatureParams = url.includes('Signature=') && url.includes('Policy=') && url.includes('Key-Pair-Id=')\n\n const constructedUrl = !hasSignatureParams ?`${url}${firstParamConnector}Signature=${Signature}&Policy=${Policy}&Key-Pair-Id=${KeyPairId}` : url\n\n console.debug('Fetching image via CloudFront For Web')\n\n const imageResponse = await fetch(constructedUrl)\n\n const contentLengthHeader = imageResponse.headers.get('content-length')\n\n if (contentLengthHeader === '0') {\n return Promise.reject(\n new Error(`Failed to fetch image as no content length: ${encodedUrl}`)\n )\n }\n\n if (!imageResponse.ok) {\n return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`))\n }\n\n return await imageResponse.arrayBuffer()\n } catch (error) {\n if (isHeader) {\n // NOTE: Replace failed headers with LH logo\n console.error('FetchImageHeaderError', error)\n return fetchLighthouseLogo()\n }\n\n console.error(error)\n return imageNotFound\n }\n}\n"],"mappings":";;AAAA,SAASA,aAAa,QAAQ,cAAc;AAC5C,SAASC,mBAAmB,QAAQ,0BAA0B;AAC9D,OAAO,IAAMC,gBAAgB;EAAA,IAAAC,IAAA,GAAAC,iBAAA,cAAAC,mBAAA,CAAAC,IAAA,CAAG,SAAAC,QAAgBC,GAAG,EAAEC,OAAO;IAAA,IAAAC,iBAAA,EAAAC,QAAA,EAAAC,SAAA,EAAAC,MAAA,EAAAC,SAAA,EAAAC,mBAAA,EAAAC,kBAAA,EAAAC,cAAA,EAAAC,aAAA,EAAAC,mBAAA,EAAAC,EAAA;IAAA,OAAAf,mBAAA,CAAAgB,IAAA,WAAAC,QAAA;MAAA,kBAAAA,QAAA,CAAAC,IAAA,GAAAD,QAAA,CAAAE,IAAA;QAAA;UAAAd,iBAAA,GACCD,OAAO,CAA1DE,QAAQ,EAARA,QAAQ,GAAAD,iBAAA,cAAG,KAAK,GAAAA,iBAAA,EAAEE,SAAS,GAAwBH,OAAO,CAAxCG,SAAS,EAAEC,MAAM,GAAgBJ,OAAO,CAA7BI,MAAM,EAAEC,SAAS,GAAKL,OAAO,CAArBK,SAAS;UAAAQ,QAAA,CAAAC,IAAA;UAI9CR,mBAAmB,GAAGP,GAAG,CAACiB,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG;UAEvDT,kBAAkB,GAAGR,GAAG,CAACkB,QAAQ,CAAC,YAAY,CAAC,IAAIlB,GAAG,CAACkB,QAAQ,CAAC,SAAS,CAAC,IAAIlB,GAAG,CAACkB,QAAQ,CAAC,cAAc,CAAC;UAE1GT,cAAc,GAAG,CAACD,kBAAkB,MAAAW,MAAA,CAAKnB,GAAG,EAAAmB,MAAA,CAA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AA;QAAA;UAAA,OAAAsB,QAAA,CAAAoB,IAAA;MAAA;IAAA,GAAAnC,OAAA;EAAA,CAEvB;EAAA,gBAtCYL,gBAAgBA,CAAAyC,EAAA,EAAAC,GAAA;IAAA,OAAAzC,IAAA,CAAA0C,KAAA,OAAAC,SAAA;EAAA;AAAA,GAsC5B","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["imageNotFound","fetchLighthouseLogo","arrayBufferToBase64","validateBase64Image","contentTypes","fetchImageForWeb","_ref","_asyncToGenerator","_regeneratorRuntime","mark","_callee","url","options","_options$isHeader","isHeader","Signature","Policy","KeyPairId","firstParamConnector","urlToEncode","encodedUrl","imageResponse","contentLengthHeader","contentType","imageType","logoArrayBuffer","base64Flag","imageStr","base64","isValid","_t","wrap","_context","prev","next","indexOf","concat","encodeURI","console","debug","fetch","sent","headers","get","abrupt","Promise","reject","Error","ok","arrayBuffer","error","stop","_x","_x2","apply","arguments"],"sources":["../../../src/helpers/fetch-image-for-web/index.js"],"sourcesContent":["import { imageNotFound } from '../../images'\nimport { fetchLighthouseLogo } from '../fetch-lighthouse-logo'\nimport { arrayBufferToBase64 } from '../fetch-image'\nimport { validateBase64Image } from '../image-validators'\nconst contentTypes = {\n 'image/png': 'png',\n 'image/jpeg': 'jpeg',\n}\n\nexport const fetchImageForWeb = async function(url, options) {\n const { isHeader = false, Signature, Policy, KeyPairId } = options\n\n try {\n const firstParamConnector = url.indexOf('?') > -1 ? '&' : '?'\n const urlToEncode = `${url}${firstParamConnector}Signature=${Signature}&Policy=${Policy}&Key-Pair-Id=${KeyPairId}`\n\n const encodedUrl = encodeURI(urlToEncode)\n\n console.debug('Fetching image via CloudFront For Web')\n\n const imageResponse = await fetch(encodedUrl)\n\n const contentLengthHeader = imageResponse.headers.get('content-length')\n const contentType = imageResponse.headers.get('content-type')\n\n if (contentLengthHeader === '0') {\n return Promise.reject(\n new Error(`Failed to fetch image as no content length: ${encodedUrl}`)\n )\n }\n\n if (!imageResponse.ok) {\n return Promise.reject(new Error(`Failed to fetch image: ${encodedUrl}`))\n }\n\n const imageType = contentTypes[contentType]\n\n const logoArrayBuffer = await imageResponse.arrayBuffer()\n\n const base64Flag = `data:image/${imageType};base64,`\n const imageStr = arrayBufferToBase64(logoArrayBuffer)\n\n const base64 = `${base64Flag}${imageStr}`\n const isValid = validateBase64Image(base64)\n\n if (!isValid) throw new Error('InvalidImageError')\n\n return base64\n } catch (error) {\n if (isHeader) {\n // NOTE: Replace failed headers with LH logo\n console.error('FetchImageHeaderError', error)\n return fetchLighthouseLogo()\n }\n\n console.error(error)\n return imageNotFound\n }\n}\n"],"mappings":";;AAAA,SAASA,aAAa,QAAQ,cAAc;AAC5C,SAASC,mBAAmB,QAAQ,0BAA0B;AAC9D,SAASC,mBAAmB,QAAQ,gBAAgB;AACpD,SAASC,mBAAmB,QAAQ,qBAAqB;AACzD,IAAMC,YAAY,GAAG;EACnB,WAAW,EAAE,KAAK;EAClB,YAAY,EAAE;AAChB,CAAC;AAED,OAAO,IAAMC,gBAAgB;EAAA,IAAAC,IAAA,GAAAC,iBAAA,cAAAC,mBAAA,CAAAC,IAAA,CAAG,SAAAC,QAAeC,GAAG,EAAEC,OAAO;IAAA,IAAAC,iBAAA,EAAAC,QAAA,EAAAC,SAAA,EAAAC,MAAA,EAAAC,SAAA,EAAAC,mBAAA,EAAAC,WAAA,EAAAC,UAAA,EAAAC,aAAA,EAAAC,mBAAA,EAAAC,WAAA,EAAAC,SAAA,EAAAC,eAAA,EAAAC,UAAA,EAAAC,QAAA,EAAAC,MAAA,EAAAC,OAAA,EAAAC,EAAA;IAAA,OAAAtB,mBAAA,CAAAuB,IAAA,WAAAC,QAAA;MAAA,kBAAAA,QAAA,CAAAC,IAAA,GAAAD,QAAA,CAAAE,IAAA;QAAA;UAAArB,iBAAA,GACED,OAAO,CAA1DE,QAAQ,EAARA,QAAQ,GAAAD,iBAAA,cAAG,KAAK,GAAAA,iBAAA,EAAEE,SAAS,GAAwBH,OAAO,CAAxC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OAEbb,aAAa,CAAC4B,WAAW,CAAC,CAAC;QAAA;UAAnDxB,eAAe,GAAAO,QAAA,CAAAS,IAAA;UAEff,UAAU,iBAAAU,MAAA,CAAiBZ,SAAS;UACpCG,QAAQ,GAAGzB,mBAAmB,CAACuB,eAAe,CAAC;UAE/CG,MAAM,MAAAQ,MAAA,CAAMV,UAAU,EAAAU,MAAA,CAAGT,QAAQ;UACjCE,OAAO,GAAG1B,mBAAmB,CAACyB,MAAM,CAAC;UAAA,IAEtCC,OAAO;YAAAG,QAAA,CAAAE,IAAA;YAAA;UAAA;UAAA,MAAQ,IAAIa,KAAK,CAAC,mBAAmB,CAAC;QAAA;UAAA,OAAAf,QAAA,CAAAY,MAAA,WAE3ChB,MAAM;QAAA;UAAAI,QAAA,CAAAC,IAAA;UAAAH,EAAA,GAAAE,QAAA;UAAA,KAETlB,QAAQ;YAAAkB,QAAA,CAAAE,IAAA;YAAA;UAAA;UACV;UACAI,OAAO,CAACY,KAAK,CAAC,uBAAuB,EAAApB,EAAO,CAAC;UAAA,OAAAE,QAAA,CAAAY,MAAA,WACtC3C,mBAAmB,CAAC,CAAC;QAAA;UAG9BqC,OAAO,CAACY,KAAK,CAAApB,EAAM,CAAC;UAAA,OAAAE,QAAA,CAAAY,MAAA,WACb5C,aAAa;QAAA;QAAA;UAAA,OAAAgC,QAAA,CAAAmB,IAAA;MAAA;IAAA,GAAAzC,OAAA;EAAA,CAEvB;EAAA,gBAjDYL,gBAAgBA,CAAA+C,EAAA,EAAAC,GAAA;IAAA,OAAA/C,IAAA,CAAAgD,KAAA,OAAAC,SAAA;EAAA;AAAA,GAiD5B","ignoreList":[]}
@@ -1,4 +1,3 @@
1
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
1
  import { find, groupBy, map, get, round } from 'lodash';
3
2
  import { buildFetchUrl } from '../';
4
3
  export function getAuditItemsData(items, data) {
@@ -7,9 +6,6 @@ export function getAuditItemsData(items, data) {
7
6
  awsS3BaseUrl = _data$settings2.awsS3BaseUrl,
8
7
  cloudinaryBaseUrl = _data$settings2.cloudinaryBaseUrl,
9
8
  cloudfrontBaseUrl = _data$settings2.cloudfrontBaseUrl,
10
- Policy = _data$settings2.Policy,
11
- KeyPairId = _data$settings2.KeyPairId,
12
- Signature = _data$settings2.Signature,
13
9
  shouldUseCloudfront = _data$settings2.shouldUseCloudfront,
14
10
  _data$entity = data.entity,
15
11
  _data$entity2 = _data$entity === void 0 ? {} : _data$entity,
@@ -51,25 +47,21 @@ export function getAuditItemsData(items, data) {
51
47
  awsS3BaseUrl: awsS3BaseUrl,
52
48
  cloudfrontBaseUrl: cloudfrontBaseUrl,
53
49
  cloudinaryBaseUrl: cloudinaryBaseUrl,
50
+ shouldUseCloudfront: shouldUseCloudfront,
51
+ fit: true,
54
52
  height: 400,
55
53
  width: 600,
56
- quality: 50,
57
- fit: true,
58
- shouldUseCloudfront: shouldUseCloudfront,
59
- Policy: Policy,
60
- KeyPairId: KeyPairId,
61
- Signature: Signature
54
+ quality: 50
62
55
  });
63
- var link = shouldUseCloudfront ? "".concat(cloudfrontBaseUrl, "/").concat(item.signedAssets[assetIndex]) : "".concat(awsS3BaseUrl, "/").concat(asset);
64
- var thumbnailUrl = buildFetchUrl(asset, _defineProperty(_defineProperty(_defineProperty(_defineProperty({
56
+ var link = "".concat(awsS3BaseUrl, "/").concat(asset);
57
+ var thumbnailUrl = buildFetchUrl(asset, {
65
58
  awsS3BaseUrl: awsS3BaseUrl,
66
59
  cloudfrontBaseUrl: cloudfrontBaseUrl,
67
60
  cloudinaryBaseUrl: cloudinaryBaseUrl,
68
61
  shouldUseCloudfront: shouldUseCloudfront,
69
62
  width: 100,
70
- quality: 50,
71
- fit: true
72
- }, "shouldUseCloudfront", shouldUseCloudfront), "Policy", Policy), "KeyPairId", KeyPairId), "Signature", Signature));
63
+ quality: 50
64
+ });
73
65
  var key = "".concat(groupIndex, "-item-asset-").concat(assetIndex);
74
66
  return {
75
67
  assetUrl: assetUrl,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["find","groupBy","map","get","round","buildFetchUrl","getAuditItemsData","items","data","_data$settings","settings","_data$settings2","awsS3BaseUrl","cloudinaryBaseUrl","cloudfrontBaseUrl","Policy","KeyPairId","Signature","shouldUseCloudfront","_data$entity","entity","_data$entity2","groupScores","groupedItems","auditData","overallActualScore","overallMaximumScore","groupIndex","key","skipped","group","title","label","groupData","groupMaximumScore","groupActualScore","groupResultScore","groupPercentageResultScore","currentGroupScores","max","actual","result","percentageResult","item","itemIndex","hasScore","score","rawAssets","assets","assetCount","length","asset","assetIndex","assetUrl","height","width","quality","fit","link","concat","signedAssets","thumbnailUrl","_defineProperty","comments","matchingScore","scores","value","scoreLabel","scoreWeight","weight","questionId","_id"],"sources":["../../../src/helpers/get-audit-items-data/index.js"],"sourcesContent":["import { find, groupBy, map, get, round } from 'lodash'\n\nimport { buildFetchUrl } from '../'\n\nexport function getAuditItemsData(items, data) {\n const {\n settings: {\n awsS3BaseUrl,\n cloudinaryBaseUrl,\n cloudfrontBaseUrl,\n Policy,\n KeyPairId,\n Signature,\n shouldUseCloudfront,\n } = {},\n entity: { groupScores } = {},\n } = data\n\n const groupedItems = groupBy(items, 'group.id')\n\n const auditData = {\n overallActualScore: 0,\n overallMaximumScore: 0,\n }\n\n auditData.items = map(groupedItems, (items, groupIndex) => {\n const key = groupIndex\n const skipped = !!items[0].group.skipped\n const title = items[0].group.label\n\n const groupData = {\n key,\n groupMaximumScore: 0,\n groupActualScore: 0,\n groupResultScore: 0,\n groupPercentageResultScore: 0,\n skipped,\n title,\n }\n\n const currentGroupScores = get(groupScores, key)\n\n if (currentGroupScores) {\n groupData.groupMaximumScore = round(currentGroupScores.max, 2)\n groupData.groupActualScore = round(currentGroupScores.actual, 2)\n groupData.groupResultScore = currentGroupScores.result\n groupData.groupPercentageResultScore = currentGroupScores.percentageResult\n }\n\n groupData.items = items.map((item, itemIndex) => {\n // NOTE: we handle scores of -1, 0 and 1\n // -1 scores are skipped from group max and actual score\n // 0 and 1 must be included in the final scores\n const hasScore = item.score !== null && item.score !== -1\n const rawAssets = item.assets || []\n const assetCount = rawAssets.length\n\n const assets = rawAssets.map((asset, assetIndex) => {\n const assetUrl = buildFetchUrl(asset, {\n awsS3BaseUrl,\n cloudfrontBaseUrl,\n cloudinaryBaseUrl,\n height: 400,\n width: 600,\n quality: 50,\n fit: true,\n shouldUseCloudfront,\n Policy,\n KeyPairId,\n Signature,\n })\n\n const link = shouldUseCloudfront\n ? `${cloudfrontBaseUrl}/${item.signedAssets[assetIndex]}`\n : `${awsS3BaseUrl}/${asset}`\n\n const thumbnailUrl = buildFetchUrl(asset, {\n awsS3BaseUrl,\n cloudfrontBaseUrl,\n cloudinaryBaseUrl,\n shouldUseCloudfront,\n width: 100,\n quality: 50,\n fit: true,\n shouldUseCloudfront,\n Policy,\n KeyPairId,\n Signature,\n })\n\n const key = `${groupIndex}-item-asset-${assetIndex}`\n\n return {\n assetUrl,\n key,\n link,\n thumbnailUrl,\n }\n })\n\n const comments = item.comments\n const label = item.label\n const score = item.score\n const key = `${groupIndex}-item-${itemIndex}`\n const matchingScore = find(item.scores, { value: score })\n\n // NOTE: ensure we have a score otherwise fallback to - value\n const scoreLabel =\n hasScore && matchingScore && !skipped ? matchingScore.label : '-'\n const scoreWeight = hasScore && !skipped ? item.scoreWeight : '-'\n const weight = hasScore ? item.weight : '-'\n\n return {\n assetCount,\n assets,\n comments,\n key,\n label,\n questionId: item._id,\n score,\n scoreLabel,\n scoreWeight,\n weight,\n }\n })\n\n return groupData\n })\n\n return auditData\n}\n"],"mappings":";AAAA,SAASA,IAAI,EAAEC,OAAO,EAAEC,GAAG,EAAEC,GAAG,EAAEC,KAAK,QAAQ,QAAQ;AAEvD,SAASC,aAAa,QAAQ,KAAK;AAEnC,OAAO,SAASC,iBAAiBA,CAACC,KAAK,EAAEC,IAAI,EAAE;EAC7C,IAAAC,cAAA,GAWID,IAAI,CAVNE,QAAQ;IAAAC,eAAA,GAAAF,cAAA,c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,UAAU;QACVD,MAAM,EAANA,MAAM;QACNe,QAAQ,EAARA,QAAQ;QACRnC,GAAG,EAAHA,GAAG;QACHI,KAAK,EAALA,KAAK;QACLsC,UAAU,EAAE3B,IAAI,CAAC4B,GAAG;QACpBzB,KAAK,EAALA,KAAK;QACLqB,UAAU,EAAVA,UAAU;QACVC,WAAW,EAAXA,WAAW;QACXC,MAAM,EAANA;MACF,CAAC;IACH,CAAC,CAAC;IAEF,OAAOpC,SAAS;EAClB,CAAC,CAAC;EAEF,OAAOT,SAAS;AAClB","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["find","groupBy","map","get","round","buildFetchUrl","getAuditItemsData","items","data","_data$settings","settings","_data$settings2","awsS3BaseUrl","cloudinaryBaseUrl","cloudfrontBaseUrl","shouldUseCloudfront","_data$entity","entity","_data$entity2","groupScores","groupedItems","auditData","overallActualScore","overallMaximumScore","groupIndex","key","skipped","group","title","label","groupData","groupMaximumScore","groupActualScore","groupResultScore","groupPercentageResultScore","currentGroupScores","max","actual","result","percentageResult","item","itemIndex","hasScore","score","rawAssets","assets","assetCount","length","asset","assetIndex","assetUrl","fit","height","width","quality","link","concat","thumbnailUrl","comments","matchingScore","scores","value","scoreLabel","scoreWeight","weight","questionId","_id"],"sources":["../../../src/helpers/get-audit-items-data/index.js"],"sourcesContent":["import { find, groupBy, map, get, round } from 'lodash'\n\nimport { buildFetchUrl } from '../'\n\nexport function getAuditItemsData(items, data) {\n const {\n settings: {\n awsS3BaseUrl,\n cloudinaryBaseUrl,\n cloudfrontBaseUrl,\n shouldUseCloudfront,\n } = {},\n entity: { groupScores } = {},\n } = data\n\n const groupedItems = groupBy(items, 'group.id')\n\n const auditData = {\n overallActualScore: 0,\n overallMaximumScore: 0,\n }\n\n auditData.items = map(groupedItems, (items, groupIndex) => {\n const key = groupIndex\n const skipped = !!items[0].group.skipped\n const title = items[0].group.label\n\n const groupData = {\n key,\n groupMaximumScore: 0,\n groupActualScore: 0,\n groupResultScore: 0,\n groupPercentageResultScore: 0,\n skipped,\n title,\n }\n\n const currentGroupScores = get(groupScores, key)\n\n if (currentGroupScores) {\n groupData.groupMaximumScore = round(currentGroupScores.max, 2)\n groupData.groupActualScore = round(currentGroupScores.actual, 2)\n groupData.groupResultScore = currentGroupScores.result\n groupData.groupPercentageResultScore = currentGroupScores.percentageResult\n }\n\n groupData.items = items.map((item, itemIndex) => {\n // NOTE: we handle scores of -1, 0 and 1\n // -1 scores are skipped from group max and actual score\n // 0 and 1 must be included in the final scores\n const hasScore = item.score !== null && item.score !== -1\n const rawAssets = item.assets || []\n const assetCount = rawAssets.length\n\n const assets = rawAssets.map((asset, assetIndex) => {\n const assetUrl = buildFetchUrl(asset, {\n awsS3BaseUrl,\n cloudfrontBaseUrl,\n cloudinaryBaseUrl,\n shouldUseCloudfront,\n fit: true,\n height: 400,\n width: 600,\n quality: 50,\n })\n\n const link = `${awsS3BaseUrl}/${asset}`\n\n const thumbnailUrl = buildFetchUrl(asset, {\n awsS3BaseUrl,\n cloudfrontBaseUrl,\n cloudinaryBaseUrl,\n shouldUseCloudfront,\n width: 100,\n quality: 50,\n })\n\n const key = `${groupIndex}-item-asset-${assetIndex}`\n\n return {\n assetUrl,\n key,\n link,\n thumbnailUrl,\n }\n })\n\n const comments = item.comments\n const label = item.label\n const score = item.score\n const key = `${groupIndex}-item-${itemIndex}`\n const matchingScore = find(item.scores, { value: score })\n\n // NOTE: ensure we have a score otherwise fallback to - value\n const scoreLabel =\n hasScore && matchingScore && !skipped ? matchingScore.label : '-'\n const scoreWeight = hasScore && !skipped ? item.scoreWeight : '-'\n const weight = hasScore ? item.weight : '-'\n\n return {\n assetCount,\n assets,\n comments,\n key,\n label,\n questionId: item._id,\n score,\n scoreLabel,\n scoreWeight,\n weight,\n }\n })\n\n return groupData\n })\n\n return auditData\n}\n"],"mappings":"AAAA,SAASA,IAAI,EAAEC,OAAO,EAAEC,GAAG,EAAEC,GAAG,EAAEC,KAAK,QAAQ,QAAQ;AAEvD,SAASC,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C,CAAC;IAEF,OAAOlC,SAAS;EAClB,CAAC,CAAC;EAEF,OAAOT,SAAS;AAClB","ignoreList":[]}
@@ -192,7 +192,7 @@ function generateContent(data) {
192
192
  timezone: timezone
193
193
  });
194
194
  var promises = {
195
- entry: buildAuditContent(groupedData.items, data.settings),
195
+ entry: buildAuditContent(groupedData.items),
196
196
  footerTemplate: buildTemplateContent(footerFields.formGroups, data),
197
197
  headerTemplate: buildTemplateContent(headerFields.formGroups, data)
198
198
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Promise","isEmpty","round","moment","buildAuditContent","buildAuditFollowUps","buildTemplateContent","generateDefinition","getFormattedAddress","horizontalLine","text","twoColumnTable","getAuditEntryDetails","buildAuditPdf","pdfOptions","data","entity","timezone","_pdfOptions$flags","flags","sequenceId","timestamp","createdAt","title","fileTitle","concat","generateContent","then","content","_objectSpread","type","catch","err","Error","message","_entity$followUps","followUps","_entity$footerFields","footerFields","_entity$gps","gps","_entity$headerFields","headerFields","_entity$score","score","_entity$title","entityDetails","gpsText","groupedData","locationText","referenceValue","timezoneHourTime","scoreText","target","targetServiceLevel","renderTargetFields","headerTitle","style","headerScore","alignment","firstRow","subTitle","headerSubTitle","colSpan","secondRow","reverseGeocoded","address","renderHeaderAddress","dummyColumn","headerAddress","renderThirdRow","thirdRow","serviceLevelBelow","serviceLevelText","scoreServiceLevelSubTitle","truncatedTargetPercent","scoreTargetText","scoreTargetSubTitle","scoreBreakdown","actual","max","scorePercentage","scoreTitle","body","submittedAtInTimezone","submittedAt","tz","format","showSimplifiedDuration","push","startedAtInTimezone","startedAt","momentDuration","duration","Math","abs","formDuration","days","floor","asDays","toString","padStart","hours","minutes","seconds","formattedFormDuration","titleTable","layout","widths","margin","totalScoreTable","hLineTop","hLineBottom","followUpItems","promises","entry","items","settings","footerTemplate","formGroups","headerTemplate","auditItemsTitle","font","lineHeight","props","_ref","_toConsumableArray"],"sources":["../../../src/pdf/audit/index.js"],"sourcesContent":["import Promise from 'bluebird'\nimport { isEmpty, round } from 'lodash'\nimport moment from 'moment-timezone'\n\nimport {\n buildAuditContent,\n buildAuditFollowUps,\n buildTemplateContent,\n generateDefinition,\n getFormattedAddress,\n horizontalLine,\n text,\n twoColumnTable,\n} from '../helpers'\nimport { getAuditEntryDetails } from '../../helpers'\n\n/**\n * buildAuditPdf\n *\n * @param {object} pdfOptions - the pdf options\n * @param {string} pdfOptions.fileTitle - pdf file title\n * @param {function} pdfOptions.footer - function executed to generate footer\n * @param {function} pdfOptions.header - function executed to generate header\n * @param {string} pdfOptions.logoUrl - pdf logo url\n * @param {array} pdfOptions.pageMargins - pdf page margins\n * @param {string} pdfOptions.pageOrientation - pdf page orientation\n * @param {string} pdfOptions.pageSize - pdf page size\n * @param {object} pdfOptions.styles - pdf styles\n * @param {object} pdfOptions.title - pdf title\n * @param {object} pdfOptions.flags - flags to conditionally render parts of the pdf\n * @param {object} data - pdf data\n * @param {object} data.entity - audit document\n * @param {object} data.locations - locations documents\n * @param {object} data.settings - settings properties\n * @param {string} data.settings.awsS3BaseUrl - aws S3 base url\n * @param {string} data.settings.cloudinaryBaseUrl - cloudinary base url\n * @param {string} data.timezone - timezone string\n * @param {object} data.users - application user documents\n * @returns {Promise} returns pdfmake definition object\n */\nexport function buildAuditPdf(pdfOptions, data) {\n const { entity, timezone } = data\n const { flags = {} } = pdfOptions\n\n const sequenceId = entity.sequenceId\n const timestamp = entity.createdAt\n const title = entity.title || 'Unknown'\n const fileTitle = `Audit Report - ${title}`\n\n return generateContent(data, flags)\n .then((content) =>\n generateDefinition({\n content,\n fileTitle,\n sequenceId,\n timestamp,\n timezone,\n type: 'Audit',\n ...pdfOptions,\n })\n )\n .catch((err) => {\n throw new Error(`BuildAuditPdfError: ${err.message}`)\n })\n}\n\nfunction generateContent(data) {\n const { entity } = data\n\n const {\n followUps = [],\n footerFields = {},\n gps = {},\n headerFields = {},\n score = {},\n title = 'Unknown',\n } = entity\n\n const timezone = entity?.timezone || data?.timezone || 'UTC'\n const entityDetails = getAuditEntryDetails(data)\n\n const {\n gpsText,\n groupedData,\n locationText,\n referenceValue,\n timezoneHourTime,\n scoreText,\n target,\n targetServiceLevel,\n } = entityDetails\n\n const renderTargetFields = !!targetServiceLevel\n const headerTitle = text(title, { style: 'title' })\n const headerScore = text(scoreText, { alignment: 'right', style: 'title' })\n const firstRow = [headerTitle, headerScore]\n const subTitle = `${\n locationText || gpsText\n } - ${timezoneHourTime} by ${referenceValue}`\n\n let headerSubTitle = text(subTitle, { colSpan: 2, style: 'subTitle' })\n let secondRow = [headerSubTitle]\n\n const reverseGeocoded = gps.reverseGeocoded\n const address = !isEmpty(reverseGeocoded)\n ? getFormattedAddress(reverseGeocoded)\n : ''\n const renderHeaderAddress = !isEmpty(reverseGeocoded)\n const dummyColumn = text(' ', { style: 'small' })\n\n let headerAddress = text(address, { colSpan: 2, style: 'small' })\n const renderThirdRow = renderHeaderAddress || renderTargetFields\n let thirdRow = renderHeaderAddress ? [headerAddress] : []\n\n if (renderTargetFields) {\n headerSubTitle = text(subTitle, { style: 'subTitle' })\n\n const serviceLevelBelow = targetServiceLevel === 'below'\n const serviceLevelText =\n targetServiceLevel === 'above'\n ? 'Above Target'\n : targetServiceLevel === 'on'\n ? 'On Target'\n : targetServiceLevel === 'below'\n ? 'Below Target'\n : ''\n\n const scoreServiceLevelSubTitle = text(serviceLevelText, {\n alignment: 'right',\n style: serviceLevelBelow ? 'serviceLevelBelow' : 'serviceLevelAboveOrOn',\n })\n\n secondRow = [headerSubTitle, scoreServiceLevelSubTitle]\n headerAddress = text(address, { style: 'small' })\n\n const truncatedTargetPercent = round(target, 2)\n const scoreTargetText = `(Target - ${truncatedTargetPercent}%)`\n const scoreTargetSubTitle = text(scoreTargetText, {\n alignment: 'right',\n style: 'subTitle',\n })\n\n thirdRow = renderHeaderAddress\n ? [headerAddress, scoreTargetSubTitle]\n : [dummyColumn, scoreTargetSubTitle]\n }\n\n const scoreBreakdown = text(\n `${round(score.actual, 2)} / ${round(score.max, 2)}`,\n {\n alignment: 'right',\n style: 'totalScore',\n }\n )\n const scorePercentage = text(scoreText, {\n alignment: 'right',\n colSpan: 2,\n style: 'totalAuditScore',\n })\n const scoreTitle = text('Total Score', { style: 'totalScore' })\n\n const body = renderThirdRow\n ? [firstRow, secondRow, thirdRow]\n : [firstRow, secondRow]\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt).tz(timezone).format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n if (entity.showSimplifiedDuration) {\n body.push([submittedAt, dummyColumn])\n } else {\n const startedAtInTimezone = entity.startedAt\n ? moment(entity.startedAt).tz(timezone).format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const startedAt = text(`Started: ${startedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt).tz(timezone).format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const momentDuration = moment.duration(Math.abs(entity.formDuration))\n const days = Math.floor(momentDuration.asDays()).toString().padStart(2, '0')\n const hours = Math.floor(momentDuration.hours()).toString().padStart(2, '0')\n const minutes = momentDuration.minutes().toString().padStart(2, '0')\n const seconds = momentDuration.seconds().toString().padStart(2, '0')\n const formattedFormDuration = entity.formDuration\n ? `${\n entity.formDuration < 0 ? '-' : ''\n }${days}:${hours}:${minutes}:${seconds}`\n : 'Not recorded'\n const formDuration = text(\n `Form Duration (DD:HH:MM:SS): ${formattedFormDuration}`,\n {\n colSpan: 2,\n style: 'small',\n }\n )\n\n body.push([startedAt, dummyColumn])\n body.push([submittedAt, dummyColumn])\n body.push([formDuration, dummyColumn])\n }\n\n const titleTable = twoColumnTable({\n body,\n layout: 'noBorders',\n style: 'titleTable',\n widths: ['*', 100],\n margin: [0, 0, 0, 30],\n })\n\n const totalScoreTable = twoColumnTable({\n body: [[scoreTitle, scoreBreakdown], [scorePercentage]],\n layout: 'noBorders',\n widths: ['*', 100],\n })\n\n const hLineTop = horizontalLine({ margin: [0, 10, 0, 0] })\n const hLineBottom = horizontalLine()\n\n const followUpItems = buildAuditFollowUps(followUps, { timezone })\n\n const promises = {\n entry: buildAuditContent(groupedData.items, data.settings),\n footerTemplate: buildTemplateContent(footerFields.formGroups, data),\n headerTemplate: buildTemplateContent(headerFields.formGroups, data),\n }\n\n const auditItemsTitle = [\n {\n text: 'Audit Items',\n style: {\n font: 'Gotham',\n lineHeight: 1.1,\n },\n },\n hLineTop,\n ]\n\n return Promise.props(promises)\n .then(({ entry, footerTemplate, headerTemplate }) => [\n titleTable,\n followUpItems,\n ...auditItemsTitle,\n ...headerTemplate,\n ...entry,\n hLineTop,\n totalScoreTable,\n hLineBottom,\n ...footerTemplate,\n ])\n .catch((err) => {\n throw new Error(`GenerateContentError: ${err.message}`)\n })\n}\n"],"mappings":";;;;AAAA,OAAOA,OAAO,MAAM,UAAU;AAC9B,SAASC,OAAO,EAAEC,KAAK,QAAQ,QAAQ;AACvC,OAAOC,MAAM,MAAM,iBAAiB;AAEpC,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,EACnBC,cAAc,EACdC,IAAI,EACJC,cAAc,QACT,YAAY;AACnB,SAASC,oBAAoB,QAAQ,eAAe;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAACC,UAAU,EAAEC,IAAI,EAAE;EAC9C,IAAQC,MAAM,GAAeD,IAAI,CAAzBC,MAAM;IAAEC,QAAQ,GAAKF,IAAI,CAAjBE,QAAQ;EACxB,IAAAC,iBAAA,GAAuB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AC,UAACC,GAAG,EAAK;IACd,MAAM,IAAIC,KAAK,0BAAAR,MAAA,CAA0BO,GAAG,CAACE,OAAO,CAAE,CAAC;EACzD,CAAC,CAAC;AACN","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["Promise","isEmpty","round","moment","buildAuditContent","buildAuditFollowUps","buildTemplateContent","generateDefinition","getFormattedAddress","horizontalLine","text","twoColumnTable","getAuditEntryDetails","buildAuditPdf","pdfOptions","data","entity","timezone","_pdfOptions$flags","flags","sequenceId","timestamp","createdAt","title","fileTitle","concat","generateContent","then","content","_objectSpread","type","catch","err","Error","message","_entity$followUps","followUps","_entity$footerFields","footerFields","_entity$gps","gps","_entity$headerFields","headerFields","_entity$score","score","_entity$title","entityDetails","gpsText","groupedData","locationText","referenceValue","timezoneHourTime","scoreText","target","targetServiceLevel","renderTargetFields","headerTitle","style","headerScore","alignment","firstRow","subTitle","headerSubTitle","colSpan","secondRow","reverseGeocoded","address","renderHeaderAddress","dummyColumn","headerAddress","renderThirdRow","thirdRow","serviceLevelBelow","serviceLevelText","scoreServiceLevelSubTitle","truncatedTargetPercent","scoreTargetText","scoreTargetSubTitle","scoreBreakdown","actual","max","scorePercentage","scoreTitle","body","submittedAtInTimezone","submittedAt","tz","format","showSimplifiedDuration","push","startedAtInTimezone","startedAt","momentDuration","duration","Math","abs","formDuration","days","floor","asDays","toString","padStart","hours","minutes","seconds","formattedFormDuration","titleTable","layout","widths","margin","totalScoreTable","hLineTop","hLineBottom","followUpItems","promises","entry","items","footerTemplate","formGroups","headerTemplate","auditItemsTitle","font","lineHeight","props","_ref","_toConsumableArray"],"sources":["../../../src/pdf/audit/index.js"],"sourcesContent":["import Promise from 'bluebird'\nimport { isEmpty, round } from 'lodash'\nimport moment from 'moment-timezone'\n\nimport {\n buildAuditContent,\n buildAuditFollowUps,\n buildTemplateContent,\n generateDefinition,\n getFormattedAddress,\n horizontalLine,\n text,\n twoColumnTable,\n} from '../helpers'\nimport { getAuditEntryDetails } from '../../helpers'\n\n/**\n * buildAuditPdf\n *\n * @param {object} pdfOptions - the pdf options\n * @param {string} pdfOptions.fileTitle - pdf file title\n * @param {function} pdfOptions.footer - function executed to generate footer\n * @param {function} pdfOptions.header - function executed to generate header\n * @param {string} pdfOptions.logoUrl - pdf logo url\n * @param {array} pdfOptions.pageMargins - pdf page margins\n * @param {string} pdfOptions.pageOrientation - pdf page orientation\n * @param {string} pdfOptions.pageSize - pdf page size\n * @param {object} pdfOptions.styles - pdf styles\n * @param {object} pdfOptions.title - pdf title\n * @param {object} pdfOptions.flags - flags to conditionally render parts of the pdf\n * @param {object} data - pdf data\n * @param {object} data.entity - audit document\n * @param {object} data.locations - locations documents\n * @param {object} data.settings - settings properties\n * @param {string} data.settings.awsS3BaseUrl - aws S3 base url\n * @param {string} data.settings.cloudinaryBaseUrl - cloudinary base url\n * @param {string} data.timezone - timezone string\n * @param {object} data.users - application user documents\n * @returns {Promise} returns pdfmake definition object\n */\nexport function buildAuditPdf(pdfOptions, data) {\n const { entity, timezone } = data\n const { flags = {} } = pdfOptions\n\n const sequenceId = entity.sequenceId\n const timestamp = entity.createdAt\n const title = entity.title || 'Unknown'\n const fileTitle = `Audit Report - ${title}`\n\n return generateContent(data, flags)\n .then(content =>\n generateDefinition({\n content,\n fileTitle,\n sequenceId,\n timestamp,\n timezone,\n type: 'Audit',\n ...pdfOptions,\n })\n )\n .catch(err => {\n throw new Error(`BuildAuditPdfError: ${err.message}`)\n })\n}\n\nfunction generateContent(data) {\n const { entity } = data\n\n const {\n followUps = [],\n footerFields = {},\n gps = {},\n headerFields = {},\n score = {},\n title = 'Unknown',\n } = entity\n\n const timezone = entity?.timezone || data?.timezone || 'UTC'\n const entityDetails = getAuditEntryDetails(data)\n\n const {\n gpsText,\n groupedData,\n locationText,\n referenceValue,\n timezoneHourTime,\n scoreText,\n target,\n targetServiceLevel,\n } = entityDetails\n\n const renderTargetFields = !!targetServiceLevel\n const headerTitle = text(title, { style: 'title' })\n const headerScore = text(scoreText, { alignment: 'right', style: 'title' })\n const firstRow = [headerTitle, headerScore]\n const subTitle = `${locationText ||\n gpsText} - ${timezoneHourTime} by ${referenceValue}`\n\n let headerSubTitle = text(subTitle, { colSpan: 2, style: 'subTitle' })\n let secondRow = [headerSubTitle]\n\n const reverseGeocoded = gps.reverseGeocoded\n const address = !isEmpty(reverseGeocoded)\n ? getFormattedAddress(reverseGeocoded)\n : ''\n const renderHeaderAddress = !isEmpty(reverseGeocoded)\n const dummyColumn = text(' ', { style: 'small' })\n\n let headerAddress = text(address, { colSpan: 2, style: 'small' })\n const renderThirdRow = renderHeaderAddress || renderTargetFields\n let thirdRow = renderHeaderAddress ? [headerAddress] : []\n\n if (renderTargetFields) {\n headerSubTitle = text(subTitle, { style: 'subTitle' })\n\n const serviceLevelBelow = targetServiceLevel === 'below'\n const serviceLevelText =\n targetServiceLevel === 'above'\n ? 'Above Target'\n : targetServiceLevel === 'on'\n ? 'On Target'\n : targetServiceLevel === 'below'\n ? 'Below Target'\n : ''\n\n const scoreServiceLevelSubTitle = text(serviceLevelText, {\n alignment: 'right',\n style: serviceLevelBelow ? 'serviceLevelBelow' : 'serviceLevelAboveOrOn',\n })\n\n secondRow = [headerSubTitle, scoreServiceLevelSubTitle]\n headerAddress = text(address, { style: 'small' })\n\n const truncatedTargetPercent = round(target, 2)\n const scoreTargetText = `(Target - ${truncatedTargetPercent}%)`\n const scoreTargetSubTitle = text(scoreTargetText, {\n alignment: 'right',\n style: 'subTitle',\n })\n\n thirdRow = renderHeaderAddress\n ? [headerAddress, scoreTargetSubTitle]\n : [dummyColumn, scoreTargetSubTitle]\n }\n\n const scoreBreakdown = text(\n `${round(score.actual, 2)} / ${round(score.max, 2)}`,\n {\n alignment: 'right',\n style: 'totalScore',\n }\n )\n const scorePercentage = text(scoreText, {\n alignment: 'right',\n colSpan: 2,\n style: 'totalAuditScore',\n })\n const scoreTitle = text('Total Score', { style: 'totalScore' })\n\n const body = renderThirdRow\n ? [firstRow, secondRow, thirdRow]\n : [firstRow, secondRow]\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n if (entity.showSimplifiedDuration) {\n body.push([submittedAt, dummyColumn])\n } else {\n const startedAtInTimezone = entity.startedAt\n ? moment(entity.startedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const startedAt = text(`Started: ${startedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const submittedAtInTimezone = entity.submittedAt\n ? moment(entity.submittedAt)\n .tz(timezone)\n .format('YYYY-MM-DD HH:mm:ss z')\n : 'Not recorded'\n const submittedAt = text(`Submitted: ${submittedAtInTimezone}`, {\n colSpan: 2,\n style: 'small',\n })\n\n const momentDuration = moment.duration(Math.abs(entity.formDuration))\n const days = Math.floor(momentDuration.asDays())\n .toString()\n .padStart(2, '0')\n const hours = Math.floor(momentDuration.hours())\n .toString()\n .padStart(2, '0')\n const minutes = momentDuration\n .minutes()\n .toString()\n .padStart(2, '0')\n const seconds = momentDuration\n .seconds()\n .toString()\n .padStart(2, '0')\n const formattedFormDuration = entity.formDuration\n ? `${\n entity.formDuration < 0 ? '-' : ''\n }${days}:${hours}:${minutes}:${seconds}`\n : 'Not recorded'\n const formDuration = text(\n `Form Duration (DD:HH:MM:SS): ${formattedFormDuration}`,\n {\n colSpan: 2,\n style: 'small',\n }\n )\n\n body.push([startedAt, dummyColumn])\n body.push([submittedAt, dummyColumn])\n body.push([formDuration, dummyColumn])\n }\n\n const titleTable = twoColumnTable({\n body,\n layout: 'noBorders',\n style: 'titleTable',\n widths: ['*', 100],\n margin: [0, 0, 0, 30],\n })\n\n const totalScoreTable = twoColumnTable({\n body: [[scoreTitle, scoreBreakdown], [scorePercentage]],\n layout: 'noBorders',\n widths: ['*', 100],\n })\n\n const hLineTop = horizontalLine({ margin: [0, 10, 0, 0] })\n const hLineBottom = horizontalLine()\n\n const followUpItems = buildAuditFollowUps(followUps, { timezone })\n\n const promises = {\n entry: buildAuditContent(groupedData.items),\n footerTemplate: buildTemplateContent(footerFields.formGroups, data),\n headerTemplate: buildTemplateContent(headerFields.formGroups, data),\n }\n\n const auditItemsTitle = [\n {\n text: 'Audit Items',\n style: {\n font: 'Gotham',\n lineHeight: 1.1,\n },\n },\n hLineTop,\n ]\n\n return Promise.props(promises)\n .then(({ entry, footerTemplate, headerTemplate }) => [\n titleTable,\n followUpItems,\n ...auditItemsTitle,\n ...headerTemplate,\n ...entry,\n hLineTop,\n totalScoreTable,\n hLineBottom,\n ...footerTemplate,\n ])\n .catch(err => {\n throw new Error(`GenerateContentError: ${err.message}`)\n })\n}\n"],"mappings":";;;;AAAA,OAAOA,OAAO,MAAM,UAAU;AAC9B,SAASC,OAAO,EAAEC,KAAK,QAAQ,QAAQ;AACvC,OAAOC,MAAM,MAAM,iBAAiB;AAEpC,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,EACnBC,cAAc,EACdC,IAAI,EACJC,cAAc,QACT,YAAY;AACnB,SAASC,oBAAoB,QAAQ,eAAe;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAaA,CAACC,UAAU,EAAEC,IAAI,EAAE;EAC9C,IAAQC,MAAM,GAAeD,IAAI,CAAzBC,MAAM;IAAEC,QAAQ,GAAKF,IAAI,CAAjBE,QAAQ;EACxB,IAAAC,iBAAA,GAAuBJ,UAAU,CAAzBK,KAAK;IAALA,KAAK,GAAAD,iBAAA,cAAG,CAAC,CAAC,GAAAA,iBAAA;EAElB,IAAME,UAAU,GAAGJ,MAAM,CAACI,UAAU;EACpC,IAAMC,SAA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1,11 +1,10 @@
1
1
  {
2
2
  "name": "@lighthouse/common",
3
- "version": "6.1.0-canary.8",
3
+ "version": "6.2.0-canary.1",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "lib/index.js",
7
7
  "scripts": {
8
- "watch": "yarn clear:es && babel src --out-dir lib --extensions '.js,.ts' --ignore 'src/**/fixtures.js,src/**/fixtures/*,src/**/*.story.js,src/**/*.story.ts,src/**/*.test.js,src/**/*.test.ts' --source-maps --watch",
9
8
  "build": "yarn clear && yarn build:es && yarn build:node",
10
9
  "build:es": "yarn clear:es && babel src --out-dir lib --extensions '.js,.ts' --ignore 'src/**/fixtures.js,src/**/fixtures/*,src/**/*.story.js,src/**/*.story.ts,src/**/*.test.js,src/**/*.test.ts' --source-maps",
11
10
  "build:node": "yarn clear:node && BABEL_ENV=node babel src --out-dir dist --extensions '.js,.ts' --ignore 'src/**/fixtures.js,src/**/fixtures/*,src/**/*.story.js,src/**/*.story.ts,src/**/*.test.js,src/**/*.test.ts'",