Best JavaScript code snippet using chromeless
aws-website-resource.ts
Source:aws-website-resource.ts  
...74    if (tags === undefined) {75      // The bucket doesn't exist yet76      logMessage(`Creating the S3 bucket...`);77      const params: AWS.S3.CreateBucketRequest = {78        Bucket: this.getS3BucketName(),79        ACL: 'public-read'80      };81      if (config.aws.region !== 'us-east-1') {82        params.CreateBucketConfiguration = {LocationConstraint: config.aws.region};83      }84      await s3.createBucket(params).promise();85      await s386        .putBucketTagging({87          Bucket: this.getS3BucketName(),88          Tagging: {TagSet: [{Key: 'managed-by', Value: MANAGER_IDENTIFIER}]}89        })90        .promise();91      await s392        .putBucketWebsite({93          Bucket: this.getS3BucketName(),94          WebsiteConfiguration: {IndexDocument: {Suffix: config.indexPage}}95        })96        .promise();97      await s3.waitFor('bucketExists', {Bucket: this.getS3BucketName()}).promise();98    } else {99      // The bucket already exists100      if (!tags.some((tag) => isEqual(tag, {Key: 'managed-by', Value: MANAGER_IDENTIFIER}))) {101        throwError(102          `Cannot use a S3 bucket that was not originally created by this tool (bucket name: '${this.getS3BucketName()}')`103        );104      }105      const locationConstraint =106        (await s3.getBucketLocation({Bucket: this.getS3BucketName()}).promise())107          .LocationConstraint || 'us-east-1';108      if (locationConstraint !== config.aws.region) {109        throwError(110          `Sorry, it is not currently possible to change the region of a S3 bucket. Please remove the bucket '${this.getS3BucketName()}' manually or set 'aws.region' to '${locationConstraint}'.`111        );112      }113      const websiteConfiguration = await s3114        .getBucketWebsite({Bucket: this.getS3BucketName()})115        .promise();116      if (websiteConfiguration.IndexDocument?.Suffix !== config.indexPage) {117        logMessage(`Updating the S3 bucket website configuration...`);118        websiteConfiguration.IndexDocument = {Suffix: config.indexPage};119        await s3120          .putBucketWebsite({121            Bucket: this.getS3BucketName(),122            WebsiteConfiguration: websiteConfiguration123          })124          .promise();125      }126    }127  }128  async getS3BucketTags() {129    const s3 = this.getS3Client();130    try {131      return (await s3.getBucketTagging({Bucket: this.getS3BucketName()}).promise()).TagSet;132    } catch (err) {133      if (err.code === 'NoSuchTagSet') {134        return [];135      }136      if (err.code === 'NoSuchBucket') {137        return undefined;138      }139      if (err.code === 'AccessDenied') {140        throwError(`Access denied to the S3 bucket '${this.getS3BucketName()}'`);141      }142      throw err;143    }144  }145  async synchronizeFiles() {146    const config = this.getConfig();147    const s3 = this.getS3Client();148    logMessage(`Synchronizing the files...`);149    const files = getFilesFromFileSpecifiers(config.directory, config.files);150    const previousConfig = await this.loadConfigFromS3();151    const s3Files = await this.listS3Files();152    const changes = new Array<string>();153    let addedFiles = 0;154    let updatedFiles = 0;155    let removedFiles = 0;156    for (const {directory, file} of files) {157      const absoluteFile = join(directory, file);158      const md5 = hasha.fromFileSync(absoluteFile, {algorithm: 'md5'});159      const size = statSync(absoluteFile).size;160      const isImmutable = matchFilePatterns(file, config.immutableFiles);161      let s3File: {path: string; size: number; md5: string} | undefined;162      const index = s3Files.findIndex(({path}) => path === file);163      if (index !== -1) {164        s3File = s3Files[index];165        s3Files.splice(index, 1);166      }167      if (s3File !== undefined && s3File.size === size && s3File.md5 === md5) {168        const wasImmutable = matchFilePatterns(file, previousConfig.immutableFiles);169        if (isImmutable === wasImmutable) {170          continue; // No changes171        }172      }173      logMessage(`Uploading '${file}' (${bytes(size)}) to S3...`);174      const params: AWS.S3.PutObjectRequest = {175        Bucket: this.getS3BucketName(),176        Key: file,177        ACL: 'public-read',178        Body: createReadStream(absoluteFile),179        ContentType: mime.getType(file) ?? 'application/octet-stream',180        ContentMD5: Buffer.from(md5, 'hex').toString('base64')181      };182      if (isImmutable) {183        params.CacheControl = `max-age=${IMMUTABLE_FILES_MAX_AGE}`;184      }185      await s3.putObject(params).promise();186      if (s3File === undefined) {187        addedFiles++;188      } else {189        updatedFiles++;190      }191      changes.push(file);192    }193    for (const s3File of s3Files) {194      logMessage(`Removing '${s3File.path}' from S3...`);195      await s3.deleteObject({Bucket: this.getS3BucketName(), Key: s3File.path}).promise();196      removedFiles++;197      changes.push(s3File.path);198    }199    if (!isEqual(config, previousConfig)) {200      await this.saveConfigToS3();201    }202    let info = '';203    const buildInfo = (operation: string, fileCount: number) => {204      if (fileCount === 0) {205        return;206      }207      if (info !== '') {208        info += ', ';209      }210      info += `${fileCount} file`;211      if (fileCount > 1) {212        info += 's';213      }214      info += ` ${operation}`;215    };216    buildInfo('added', addedFiles);217    buildInfo('updated', updatedFiles);218    buildInfo('removed', removedFiles);219    if (info === '') {220      info = 'no changes';221    }222    logMessage(`Synchronization completed (${info})`);223    return changes;224  }225  async listS3Files() {226    const s3 = this.getS3Client();227    logMessage(`Listing the existing files in S3...`);228    const files = [];229    let nextContinuationToken: string | undefined;230    do {231      const result = await s3232        .listObjectsV2({233          Bucket: this.getS3BucketName(),234          ContinuationToken: nextContinuationToken235        })236        .promise();237      for (const item of result.Contents!) {238        const path = item.Key!;239        const size = item.Size!;240        const md5 = item.ETag!.slice(1, -1);241        if (path[0] !== '.') {242          files.push({path, size, md5});243        }244      }245      nextContinuationToken = result.NextContinuationToken;246    } while (nextContinuationToken);247    return files;248  }249  async loadConfigFromS3() {250    const s3 = this.getS3Client();251    try {252      const result = await s3253        .getObject({254          Bucket: this.getS3BucketName(),255          Key: CONFIG_FILE_S3_KEY256        })257        .promise();258      return JSON.parse(result.Body as string);259    } catch (err) {260      if (err.code === 'NoSuchKey') {261        return {};262      }263      throw err;264    }265  }266  async saveConfigToS3() {267    const config = this.getConfig();268    const s3 = this.getS3Client();269    const body = JSON.stringify(config);270    const md5 = hasha(body, {algorithm: 'md5'});271    const contentMD5 = Buffer.from(md5, 'hex').toString('base64');272    await s3273      .putObject({274        Bucket: this.getS3BucketName(),275        Key: CONFIG_FILE_S3_KEY,276        Body: body,277        ContentType: 'application/json',278        ContentMD5: contentMD5279      })280      .promise();281  }282  getS3BucketName() {283    return this.getConfig().domainName;284  }285  // === CloudFront ===286  async createOrUpdateCloudFrontDistribution() {287    let hasBeenCreated;288    let status = await this.checkCloudFrontDistribution();289    if (status === 'NOT_FOUND') {290      await this.createCloudFrontDistribution();291      hasBeenCreated = true;292      status = 'DEPLOYING';293    } else if (status === 'NEEDS_UPDATE') {294      await this.updateCloudFrontDistribution();295      status = 'DEPLOYING';296    }297    if (status === 'DEPLOYING') {298      await this.waitForCloudFrontDistributionDeployment();299    }300    return hasBeenCreated;301  }302  async checkCloudFrontDistribution() {303    logMessage(`Checking the CloudFront distribution...`);304    const distribution = await this.getCloudFrontDistribution();305    if (distribution === undefined) {306      return 'NOT_FOUND';307    }308    await this.checkCloudFrontDistributionTags();309    if (!distribution.Enabled) {310      throwError(`The CloudFront distribution is disabled (ARN: '${distribution.ARN}')`);311    }312    if (await this.checkIfCloudFrontDistributionNeedsUpdate()) {313      return 'NEEDS_UPDATE';314    }315    if (distribution.Status !== 'Deployed') {316      return 'DEPLOYING';317    }318    return 'OKAY';319  }320  _cloudFrontDistribution?: AWS.CloudFront.DistributionSummary;321  async getCloudFrontDistribution() {322    if (this._cloudFrontDistribution === undefined) {323      const config = this.getConfig();324      const cloudFront = this.getCloudFrontClient();325      logMessage(`Searching for an existing CloudFront distribution...`);326      const result = await cloudFront.listDistributions().promise();327      for (const distribution of result.DistributionList!.Items!) {328        if (distribution.Aliases!.Items!.includes(config.domainName)) {329          this._cloudFrontDistribution = distribution;330          break;331        }332      }333      if (this._cloudFrontDistribution === undefined && result.DistributionList!.IsTruncated) {334        throwError(335          `Whoa, you have a lot of CloudFront distributions! Unfortunately, this tool cannot list them all.`336        );337      }338    }339    return this._cloudFrontDistribution;340  }341  async createCloudFrontDistribution() {342    const config = this.getConfig();343    const cloudFront = this.getCloudFrontClient();344    const certificate = await this.ensureACMCertificate({region: 'us-east-1'});345    logMessage(`Creating the CloudFront distribution...`);346    const params: AWS.CloudFront.CreateDistributionWithTagsRequest = {347      DistributionConfigWithTags: {348        DistributionConfig: {349          CallerReference: String(Date.now()),350          Aliases: {351            Quantity: 1,352            Items: [config.domainName]353          },354          DefaultRootObject: config.indexPage,355          Origins: this.generateCloudFrontDistributionOrigins(),356          DefaultCacheBehavior: this.generateCloudFrontDistributionDefaultCacheBehavior(),357          CacheBehaviors: {Quantity: 0, Items: []},358          CustomErrorResponses: this.generateCloudFrontDistributionCustomErrorResponses(),359          Comment: '',360          Logging: {Enabled: false, IncludeCookies: false, Bucket: '', Prefix: ''},361          PriceClass: config.aws.cloudFront.priceClass,362          Enabled: true,363          ViewerCertificate: {364            ACMCertificateArn: certificate.arn,365            SSLSupportMethod: 'sni-only',366            MinimumProtocolVersion: 'TLSv1',367            Certificate: certificate.arn,368            CertificateSource: 'acm'369          },370          Restrictions: {GeoRestriction: {RestrictionType: 'none', Quantity: 0, Items: []}},371          WebACLId: '',372          HttpVersion: 'http2',373          IsIPV6Enabled: true374        },375        Tags: {376          Items: [{Key: 'managed-by', Value: MANAGER_IDENTIFIER}]377        }378      }379    };380    const {Distribution: distribution} = await cloudFront381      .createDistributionWithTags(params)382      .promise();383    this._cloudFrontDistribution = (distribution as unknown) as AWS.CloudFront.DistributionSummary;384    return this._cloudFrontDistribution;385  }386  async checkIfCloudFrontDistributionNeedsUpdate() {387    const config = this.getConfig();388    const distribution = (await this.getCloudFrontDistribution())!;389    if (!isEqual(distribution.Origins, this.generateCloudFrontDistributionOrigins())) {390      return true;391    }392    if (393      !isEqual(394        distribution.DefaultCacheBehavior,395        this.generateCloudFrontDistributionDefaultCacheBehavior()396      )397    ) {398      return true;399    }400    if (401      !isEqual(402        distribution.CustomErrorResponses,403        this.generateCloudFrontDistributionCustomErrorResponses()404      )405    ) {406      return true;407    }408    if (distribution.PriceClass !== config.aws.cloudFront.priceClass) {409      return true;410    }411    return false;412  }413  async updateCloudFrontDistribution() {414    const config = this.getConfig();415    const cloudFront = this.getCloudFrontClient();416    logMessage(`Updating the CloudFront distribution...`);417    const distribution = (await this.getCloudFrontDistribution())!;418    const {DistributionConfig: distConfig, ETag: eTag} = await cloudFront419      .getDistributionConfig({420        Id: distribution.Id421      })422      .promise();423    distConfig!.Origins = this.generateCloudFrontDistributionOrigins();424    distConfig!.DefaultCacheBehavior = this.generateCloudFrontDistributionDefaultCacheBehavior();425    distConfig!.CustomErrorResponses = this.generateCloudFrontDistributionCustomErrorResponses();426    distConfig!.PriceClass = config.aws.cloudFront.priceClass;427    await cloudFront428      .updateDistribution({429        Id: distribution.Id,430        IfMatch: eTag,431        DistributionConfig: distConfig!432      })433      .promise();434  }435  generateCloudFrontDistributionOrigins() {436    const config = this.getConfig();437    return {438      Quantity: 1,439      Items: [440        {441          Id: config.domainName,442          DomainName: getS3WebsiteDomainName(this.getS3BucketName(), config.aws.region),443          OriginPath: '',444          CustomHeaders: {Quantity: 0, Items: []},445          CustomOriginConfig: {446            HTTPPort: 80,447            HTTPSPort: 443,448            OriginProtocolPolicy: 'http-only',449            OriginSslProtocols: {Quantity: 3, Items: ['TLSv1', 'TLSv1.1', 'TLSv1.2']},450            OriginReadTimeout: 30,451            OriginKeepaliveTimeout: 30452          },453          ConnectionAttempts: 3,454          ConnectionTimeout: 10,455          OriginShield: {Enabled: false}456        }...website.ts
Source:website.ts  
...89    if (tags === undefined) {90      // The bucket doesn't exist yet91      this.logMessage(`Creating the S3 bucket...`);92      const params: AWS.S3.CreateBucketRequest = {93        Bucket: this.getS3BucketName(),94        ACL: 'public-read'95      };96      if (config.region !== 'us-east-1') {97        params.CreateBucketConfiguration = {LocationConstraint: config.region};98      }99      await s3.createBucket(params).promise();100      await s3101        .putBucketTagging({102          Bucket: this.getS3BucketName(),103          Tagging: {TagSet: [{Key: 'managed-by', Value: this.constructor.managerIdentifiers[0]}]}104        })105        .promise();106      await s3107        .putBucketWebsite({108          Bucket: this.getS3BucketName(),109          WebsiteConfiguration: {IndexDocument: {Suffix: config.indexPage}}110        })111        .promise();112      await s3.waitFor('bucketExists', {Bucket: this.getS3BucketName()}).promise();113      await sleep(5000); // 5 secs114    } else {115      // The bucket already exists116      if (117        !tags.some(118          ({Key, Value}) =>119            Key === 'managed-by' && this.constructor.managerIdentifiers.includes(Value)120        )121      ) {122        this.throwError(123          `Cannot use a S3 bucket that was not originally created by this tool (bucket name: '${this.getS3BucketName()}')`124        );125      }126      const locationConstraint =127        (await s3.getBucketLocation({Bucket: this.getS3BucketName()}).promise())128          .LocationConstraint || 'us-east-1';129      if (locationConstraint !== config.region) {130        this.throwError(131          `Sorry, it is not currently possible to change the region of a S3 bucket. Please remove the bucket '${this.getS3BucketName()}' manually or set 'region' to '${locationConstraint}'.`132        );133      }134      const websiteConfiguration = await s3135        .getBucketWebsite({Bucket: this.getS3BucketName()})136        .promise();137      if (websiteConfiguration.IndexDocument?.Suffix !== config.indexPage) {138        this.logMessage(`Updating the S3 bucket website configuration...`);139        websiteConfiguration.IndexDocument = {Suffix: config.indexPage};140        await s3141          .putBucketWebsite({142            Bucket: this.getS3BucketName(),143            WebsiteConfiguration: websiteConfiguration144          })145          .promise();146      }147    }148  }149  async getS3BucketTags() {150    const s3 = this.getS3Client();151    try {152      return (await s3.getBucketTagging({Bucket: this.getS3BucketName()}).promise()).TagSet;153    } catch (err) {154      if (err.code === 'NoSuchTagSet') {155        return [];156      }157      if (err.code === 'NoSuchBucket') {158        return undefined;159      }160      if (err.code === 'AccessDenied') {161        this.throwError(`Access denied to the S3 bucket '${this.getS3BucketName()}'`);162      }163      throw err;164    }165  }166  async synchronizeFiles() {167    const config = this.getConfig();168    const s3 = this.getS3Client();169    this.logMessage(`Synchronizing the files...`);170    const files = walkSync(config.directory, {directories: false, ignore: ['**/.*']});171    const previousConfig = await this.loadConfigFromS3();172    const s3Files = await this.listS3Files();173    const changes = new Array<string>();174    let addedFiles = 0;175    let updatedFiles = 0;176    let removedFiles = 0;177    for (const file of files) {178      const absoluteFile = join(config.directory, file);179      const md5 = hasha.fromFileSync(absoluteFile, {algorithm: 'md5'});180      const size = statSync(absoluteFile).size;181      const isImmutable = matchFilePatterns(file, config.immutableFiles);182      let s3File: {path: string; size: number; md5: string} | undefined;183      const index = s3Files.findIndex(({path}) => path === file);184      if (index !== -1) {185        s3File = s3Files[index];186        s3Files.splice(index, 1);187      }188      if (s3File !== undefined && s3File.size === size && s3File.md5 === md5) {189        const wasImmutable = matchFilePatterns(file, previousConfig.immutableFiles);190        if (isImmutable === wasImmutable) {191          continue; // No changes192        }193      }194      this.logMessage(`Uploading '${file}' (${bytes(size)}) to S3...`);195      const params: AWS.S3.PutObjectRequest = {196        Bucket: this.getS3BucketName(),197        Key: file,198        ACL: 'public-read',199        Body: createReadStream(absoluteFile),200        ContentType: mime.getType(file) ?? 'application/octet-stream',201        ContentMD5: Buffer.from(md5, 'hex').toString('base64')202      };203      if (isImmutable) {204        params.CacheControl = `max-age=${IMMUTABLE_FILES_MAX_AGE}`;205      }206      await s3.putObject(params).promise();207      if (s3File === undefined) {208        addedFiles++;209      } else {210        updatedFiles++;211      }212      changes.push(file);213    }214    for (const s3File of s3Files) {215      this.logMessage(`Removing '${s3File.path}' from S3...`);216      await s3.deleteObject({Bucket: this.getS3BucketName(), Key: s3File.path}).promise();217      removedFiles++;218      changes.push(s3File.path);219    }220    if (!isEqual(config, previousConfig)) {221      await this.saveConfigToS3();222    }223    let info = '';224    const buildInfo = (operation: string, fileCount: number) => {225      if (fileCount === 0) {226        return;227      }228      if (info !== '') {229        info += ', ';230      }231      info += `${fileCount} file`;232      if (fileCount > 1) {233        info += 's';234      }235      info += ` ${operation}`;236    };237    buildInfo('added', addedFiles);238    buildInfo('updated', updatedFiles);239    buildInfo('removed', removedFiles);240    if (info === '') {241      info = 'no changes';242    }243    this.logMessage(`Synchronization completed (${info})`);244    return changes;245  }246  async listS3Files() {247    const s3 = this.getS3Client();248    this.logMessage(`Listing the existing files in S3...`);249    const files = [];250    let nextContinuationToken: string | undefined;251    do {252      const result = await s3253        .listObjectsV2({254          Bucket: this.getS3BucketName(),255          ContinuationToken: nextContinuationToken256        })257        .promise();258      for (const item of result.Contents!) {259        const path = item.Key!;260        const size = item.Size!;261        const md5 = item.ETag!.slice(1, -1);262        if (path[0] !== '.') {263          files.push({path, size, md5});264        }265      }266      nextContinuationToken = result.NextContinuationToken;267    } while (nextContinuationToken);268    return files;269  }270  async loadConfigFromS3() {271    const s3 = this.getS3Client();272    try {273      const result = await s3274        .getObject({275          Bucket: this.getS3BucketName(),276          Key: CONFIG_FILE_S3_KEY277        })278        .promise();279      return JSON.parse(result.Body as string);280    } catch (err) {281      if (err.code === 'NoSuchKey') {282        return {};283      }284      throw err;285    }286  }287  async saveConfigToS3() {288    const config = this.getConfig();289    const s3 = this.getS3Client();290    const body = JSON.stringify(config);291    const md5 = hasha(body, {algorithm: 'md5'});292    const contentMD5 = Buffer.from(md5, 'hex').toString('base64');293    await s3294      .putObject({295        Bucket: this.getS3BucketName(),296        Key: CONFIG_FILE_S3_KEY,297        Body: body,298        ContentType: 'application/json',299        ContentMD5: contentMD5300      })301      .promise();302  }303  getS3BucketName() {304    return this.getConfig().domainName;305  }306  // === CloudFront ===307  async createOrUpdateCloudFrontDistribution() {308    let hasBeenCreated;309    let status = await this.checkCloudFrontDistribution();310    if (status === 'NOT_FOUND') {311      await this.createCloudFrontDistribution();312      hasBeenCreated = true;313      status = 'DEPLOYING';314    } else if (status === 'NEEDS_UPDATE') {315      await this.updateCloudFrontDistribution();316      status = 'DEPLOYING';317    }318    if (status === 'DEPLOYING') {319      await this.waitForCloudFrontDistributionDeployment();320    }321    return hasBeenCreated;322  }323  async checkCloudFrontDistribution() {324    this.logMessage(`Checking the CloudFront distribution...`);325    const distribution = await this.getCloudFrontDistribution();326    if (distribution === undefined) {327      return 'NOT_FOUND';328    }329    await this.checkCloudFrontDistributionTags();330    if (!distribution.Enabled) {331      this.throwError(`The CloudFront distribution is disabled (ARN: '${distribution.ARN}')`);332    }333    if (await this.checkIfCloudFrontDistributionNeedsUpdate()) {334      return 'NEEDS_UPDATE';335    }336    if (distribution.Status !== 'Deployed') {337      return 'DEPLOYING';338    }339    return 'OKAY';340  }341  _cloudFrontDistribution?: AWS.CloudFront.DistributionSummary;342  async getCloudFrontDistribution() {343    if (this._cloudFrontDistribution === undefined) {344      const config = this.getConfig();345      const cloudFront = this.getCloudFrontClient();346      this.logMessage(`Searching for an existing CloudFront distribution...`);347      const result = await cloudFront.listDistributions().promise();348      for (const distribution of result.DistributionList!.Items!) {349        if (distribution.Aliases!.Items!.includes(config.domainName)) {350          this._cloudFrontDistribution = distribution;351          break;352        }353      }354      if (this._cloudFrontDistribution === undefined && result.DistributionList!.IsTruncated) {355        this.throwError(356          `Whoa, you have a lot of CloudFront distributions! Unfortunately, this tool cannot list them all.`357        );358      }359    }360    return this._cloudFrontDistribution;361  }362  async createCloudFrontDistribution() {363    const config = this.getConfig();364    const cloudFront = this.getCloudFrontClient();365    const certificate = await this.ensureACMCertificate({region: 'us-east-1'});366    this.logMessage(`Creating the CloudFront distribution...`);367    const params: AWS.CloudFront.CreateDistributionWithTagsRequest = {368      DistributionConfigWithTags: {369        DistributionConfig: {370          CallerReference: String(Date.now()),371          Aliases: {372            Quantity: 1,373            Items: [config.domainName]374          },375          DefaultRootObject: config.indexPage,376          Origins: this.generateCloudFrontDistributionOrigins(),377          DefaultCacheBehavior: this.generateCloudFrontDistributionDefaultCacheBehavior(),378          CacheBehaviors: {Quantity: 0, Items: []},379          CustomErrorResponses: CLOUDFRONT_DISTRIBUTION_CUSTOM_ERROR_RESPONSES,380          Comment: '',381          Logging: {Enabled: false, IncludeCookies: false, Bucket: '', Prefix: ''},382          PriceClass: config.cloudFront.priceClass,383          Enabled: true,384          ViewerCertificate: {385            ACMCertificateArn: certificate.arn,386            SSLSupportMethod: 'sni-only',387            MinimumProtocolVersion: 'TLSv1',388            Certificate: certificate.arn,389            CertificateSource: 'acm'390          },391          Restrictions: {GeoRestriction: {RestrictionType: 'none', Quantity: 0, Items: []}},392          WebACLId: '',393          HttpVersion: 'http2',394          IsIPV6Enabled: true395        },396        Tags: {397          Items: [{Key: 'managed-by', Value: this.constructor.managerIdentifiers[0]}]398        }399      }400    };401    const {Distribution: distribution} = await cloudFront402      .createDistributionWithTags(params)403      .promise();404    this._cloudFrontDistribution = (distribution as unknown) as AWS.CloudFront.DistributionSummary;405    return this._cloudFrontDistribution;406  }407  async checkIfCloudFrontDistributionNeedsUpdate() {408    const config = this.getConfig();409    const distribution = (await this.getCloudFrontDistribution())!;410    // if (!isEqual(distribution.Origins, this.generateCloudFrontDistributionOrigins())) {411    //   return true;412    // }413    // if (414    //   !isEqual(415    //     distribution.DefaultCacheBehavior,416    //     this.generateCloudFrontDistributionDefaultCacheBehavior()417    //   )418    // ) {419    //   return true;420    // }421    // if (422    //   !isEqual(distribution.CustomErrorResponses, CLOUDFRONT_DISTRIBUTION_CUSTOM_ERROR_RESPONSES)423    // ) {424    //   return true;425    // }426    if (distribution.PriceClass !== config.cloudFront.priceClass) {427      return true;428    }429    return false;430  }431  async updateCloudFrontDistribution() {432    const config = this.getConfig();433    const cloudFront = this.getCloudFrontClient();434    this.logMessage(`Updating the CloudFront distribution...`);435    const distribution = (await this.getCloudFrontDistribution())!;436    const {DistributionConfig: distConfig, ETag: eTag} = await cloudFront437      .getDistributionConfig({438        Id: distribution.Id439      })440      .promise();441    distConfig!.Origins = this.generateCloudFrontDistributionOrigins();442    distConfig!.DefaultCacheBehavior = this.generateCloudFrontDistributionDefaultCacheBehavior();443    distConfig!.CustomErrorResponses = CLOUDFRONT_DISTRIBUTION_CUSTOM_ERROR_RESPONSES;444    distConfig!.PriceClass = config.cloudFront.priceClass;445    await cloudFront446      .updateDistribution({447        Id: distribution.Id,448        IfMatch: eTag,449        DistributionConfig: distConfig!450      })451      .promise();452  }453  generateCloudFrontDistributionOrigins() {454    const config = this.getConfig();455    return {456      Quantity: 1,457      Items: [458        {459          Id: config.domainName,460          DomainName: getS3WebsiteDomainName(this.getS3BucketName(), config.region),461          OriginPath: '',462          CustomHeaders: {Quantity: 0, Items: []},463          CustomOriginConfig: {464            HTTPPort: 80,465            HTTPSPort: 443,466            OriginProtocolPolicy: 'http-only',467            OriginSslProtocols: {Quantity: 3, Items: ['TLSv1', 'TLSv1.1', 'TLSv1.2']},468            OriginReadTimeout: 30,469            OriginKeepaliveTimeout: 30470          },471          ConnectionAttempts: 3,472          ConnectionTimeout: 10,473          OriginShield: {Enabled: false}474        }...uploader.js
Source:uploader.js  
1const aws = require('aws-sdk');2const s3 = new aws.S3({apiVersion: '2006-03-01'});3// const uuidv4 = require('uuid/v4');4function getS3BucketName() {5  return process.env['CHROME_S3_BUCKET_NAME'];6}7function getS3BucketUrl() {8  return process.env['CHROME_S3_BUCKET_URL'];9}10function getS3ObjectKeyPrefix() {11  return process.env['CHROME_S3_OBJECT_KEY_PREFIX'] || '';12}13function getS3FilesPermissions() {14  return process.env['CHROME_S3_OBJECT_ACL'] || 'public-read';15}16// const isS3Configured = () => {17//   return getS3BucketName() && getS3BucketUrl();18// }19const s3ContentTypes = {20  'image/png': {21    extension: 'png',22  },23  'image/jpg': {24    extension: 'jpg',25  },26  'image/jpeg': {27    extension: 'jpeg',28  },29  'application/pdf': {30    extension: 'pdf',31  },32  'image/webp': {33    extension: 'webp',34  },35};36const uploadToS3 = async (37  data,38  contentType,39  // upload path won't include the extension40  uploadPath,41) => {42  const s3ContentType = s3ContentTypes[contentType];43  if (!s3ContentType) {44    throw new Error(`Unknown S3 Content type ${contentType}`);45  }46  const s3Path = `${getS3ObjectKeyPrefix()}${uploadPath}.${s3ContentType.extension}`;47  await s348    .putObject({49      Bucket: getS3BucketName(),50      Key: s3Path,51      ContentType: contentType,52      ACL: getS3FilesPermissions(),53      Body: Buffer.from(data, 'base64'),54    })55    .promise();56  // the s3Path we return needs to be encoded57  return `https://${getS3BucketUrl()}/${encodeURIComponent(s3Path)}`;58};59module.exports = {60  uploadToS3,...Using AI Code Generation
1const chromeless = require('chromeless')()2const getS3BucketName = require('./getS3BucketName')3async function run() {4    .type('chromeless', 'input[name="q"]')5    .press(13)6    .wait('#resultStats')7    .evaluate(getS3BucketName)8  await chromeless.end()9}10run().catch(console.error.bind(console))11module.exports = () => {12  const result = document.querySelector('#resultStats')13  if (result) {14  }15}Using AI Code Generation
1const chromeless = require('chromeless')()2async function run() {3    .type('input[name="s3BucketName"]', 'my-s3-bucket')4    .click('button[type="submit"]')5    .wait('#s3BucketName')6    .evaluate(() => {7      return document.querySelector('#s3BucketName').value8    })9  await chromeless.end()10}11run().catch(console.error.bind(console))12const chromeless = require('chromeless')()13async function run() {14    .type('input[name="s3BucketName"]', 'my-s3-bucket')15    .click('button[type="submit"]')16    .wait('#s3BucketName')17    .evaluate(() => {18      return document.querySelector('#s3BucketName').value19    })20  await chromeless.end()21}22run().catch(console.error.bind(console))23const chromeless = require('chromeless')()24async function run() {25    .type('input[name="s3BucketName"]', 'my-s3-bucket')26    .click('button[type="submit"]')27    .wait('#s3BucketName')28    .evaluate(() => {29      return document.querySelector('#s3BucketName').value30    })31  await chromeless.end()32}33run().catch(console.error.bind(console))34const chromeless = require('chromeless')()35async function run() {36    .type('input[name="s3BucketName"]', 'my-s3-bucket')Using AI Code Generation
1const chromeless = new Chromeless();2const s3BucketName = await chromeless.getS3BucketName();3console.log(s3BucketName);4await chromeless.end();5const Chromeless = require('chromeless').Chromeless;6const chromeless = new Chromeless();7const s3BucketName = await chromeless.getS3BucketName();8console.log(s3BucketName);9await chromeless.end();10module.exports = {11    getS3BucketName: async () => {12        const chromeless = new Chromeless();13        const s3BucketName = await chromeless.getS3BucketName();14        console.log(s3BucketName);15        await chromeless.end();16    }17}18module.exports = {19    getS3BucketName: async () => {20        const chromeless = new Chromeless();21        const s3BucketName = await chromeless.getS3BucketName();22        console.log(s3BucketName);23        await chromeless.end();24        return s3BucketName;25    }26}27const Chromeless = require('chromeless').Chromeless;28module.exports = {29    getS3BucketName: async () => {30        const chromeless = new Chromeless();31        const s3BucketName = await chromeless.getS3BucketName();32        console.log(s3BucketName);33        await chromeless.end();34        return s3BucketName;35    }36}37const Chromeless = require('chromeless').Chromeless;38module.exports = {39    getS3BucketName: async () => {40        const chromeless = new Chromeless();41        const s3BucketName = await chromeless.getS3BucketName();42        console.log(s3BucketName);43        await chromeless.end();44        return s3BucketName;45    }46}47const Chromeless = require('chromeless').Chromeless;48module.exports = {Using AI Code Generation
1const chromeless = require('./chromeless');2chromeless.getS3BucketName();3module.exports.getS3BucketName = function() {4  const AWS = require('aws-sdk');5  const s3 = new AWS.S3();6  s3.getBucketLocation({Bucket: 'myBucket'}, function(err, data) {7    if (err) return console.log(err);8    console.log(data);9  });10}11Your name to display (optional):12Your name to display (optional):13Your name to display (optional):Using AI Code Generation
1var chromeless = require('./chromeless');2var chromeless = require('chromeless');3var chromeless = new chromeless();4var getS3BucketName = function(url) {5    chromeless.goto(url)6        .evaluate(() => {7            return document.querySelector('s3BucketName').innerText;8        })9        .end();10}11module.exports.getS3BucketName = getS3BucketName;Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
