-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathclient.js
More file actions
1028 lines (912 loc) · 34.3 KB
/
Copy pathclient.js
File metadata and controls
1028 lines (912 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs';
import PercyEnv from '@percy/env';
import { git } from '@percy/env/utils';
import logger from '@percy/logger';
import Pako from 'pako';
import {
pool,
request,
formatBytes,
sha256hash,
base64encode,
getPackageJSON,
waitForTimeout,
validateTiles,
formatLogErrors,
tagsList,
normalizeBrowsers
} from './utils.js';
// Default client API URL can be set with an env var for API development
const { PERCY_CLIENT_API_URL = 'https://percy.io/api/v1' } = process.env;
let pkg = getPackageJSON(import.meta.url);
// minimum polling interval milliseconds
const MIN_POLLING_INTERVAL = 1_000;
const INVALID_TOKEN_ERROR_MESSAGE = 'Unable to retrieve snapshot details with write access token. Kindly use a full access token for retrieving snapshot details with Synchronous CLI.';
// Validate ID arguments
function validateId(type, id) {
if (!id) throw new Error(`Missing ${type} ID`);
if (!(typeof id === 'string' || typeof id === 'number')) {
throw new Error(`Invalid ${type} ID`);
}
}
function makeRegions(regions, algorithm, algorithmConfiguration) {
let regionObj;
if (algorithm) {
regionObj = {};
regionObj.algorithm = algorithm;
regionObj.configuration = algorithmConfiguration;
}
if (!Array.isArray(regions) && !regionObj) return null;
if (regionObj) {
regions ||= [];
regions.push(regionObj);
}
return regions.map(region => ({
...region,
elementSelector: region.elementSelector || { fullpage: true }
}));
}
const VISUAL_CONFIG_TOP_LEVEL_KEYS = new Set([
'enableLayout',
'percyCssValue',
'compareWithPreviousRun',
'diffIgnoreEnabled',
'diffIgnorePercentage',
'diffSensitivity',
'browsers',
'intelliIgnore'
]);
const VISUAL_CONFIG_INTELLI_IGNORE_KEYS = new Set([
'enabled',
'dynamic',
'ignoreAds',
'ignoreBanners',
'ignoreCarousels',
'ignoreCustomElementsEnabled',
'ignoreCustomElementsClasses',
'ignoreImages',
'diffIgnorePercentage'
]);
function validateBoolean(value, path) {
if (value != null && typeof value !== 'boolean') {
throw new Error(`Invalid PERCY_VISUAL_CONFIG: '${path}' must be a boolean`);
}
}
function validateNumberInRange(value, path) {
if (value == null) return;
if (typeof value !== 'number' || Number.isNaN(value) || value < 0 || value > 1) {
throw new Error(`Invalid PERCY_VISUAL_CONFIG: '${path}' must be a number between 0 and 1`);
}
}
function validateIntegerRange(value, path, min, max) {
if (value == null) return;
if (!Number.isInteger(value) || value < min || value > max) {
throw new Error(
`Invalid PERCY_VISUAL_CONFIG: '${path}' must be an integer between ${min} and ${max}`
);
}
}
function parseVisualConfigFromEnv(log) {
let rawVisualConfig = process.env.PERCY_VISUAL_CONFIG;
if (!rawVisualConfig) return;
let parsed;
try {
parsed = JSON.parse(rawVisualConfig);
} catch {
throw new Error('Invalid PERCY_VISUAL_CONFIG: value must be valid JSON');
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('Invalid PERCY_VISUAL_CONFIG: value must be a JSON object');
}
let visualConfig = {};
for (let key of Object.keys(parsed)) {
if (!VISUAL_CONFIG_TOP_LEVEL_KEYS.has(key)) {
log.warn(`Ignoring unknown PERCY_VISUAL_CONFIG key: '${key}'`);
continue;
}
visualConfig[key] = parsed[key];
}
validateBoolean(visualConfig.enableLayout, 'enableLayout');
if (visualConfig.percyCssValue != null && typeof visualConfig.percyCssValue !== 'string') {
throw new Error("Invalid PERCY_VISUAL_CONFIG: 'percyCssValue' must be a string");
}
validateBoolean(visualConfig.compareWithPreviousRun, 'compareWithPreviousRun');
validateBoolean(visualConfig.diffIgnoreEnabled, 'diffIgnoreEnabled');
validateNumberInRange(visualConfig.diffIgnorePercentage, 'diffIgnorePercentage');
validateIntegerRange(visualConfig.diffSensitivity, 'diffSensitivity', 1, 5);
if (visualConfig.browsers != null) {
if (!Array.isArray(visualConfig.browsers) || !visualConfig.browsers.every(b => typeof b === 'string')) {
throw new Error("Invalid PERCY_VISUAL_CONFIG: 'browsers' must be an array of strings");
}
visualConfig.browsers = normalizeBrowsers(visualConfig.browsers);
}
if (visualConfig.intelliIgnore != null) {
if (!visualConfig.intelliIgnore || typeof visualConfig.intelliIgnore !== 'object' ||
Array.isArray(visualConfig.intelliIgnore)) {
throw new Error("Invalid PERCY_VISUAL_CONFIG: 'intelliIgnore' must be an object");
}
let sanitizedIntelliIgnore = {};
for (let key of Object.keys(visualConfig.intelliIgnore)) {
if (!VISUAL_CONFIG_INTELLI_IGNORE_KEYS.has(key)) {
log.warn(`Ignoring unknown PERCY_VISUAL_CONFIG intelliIgnore key: '${key}'`);
continue;
}
sanitizedIntelliIgnore[key] = visualConfig.intelliIgnore[key];
}
validateBoolean(sanitizedIntelliIgnore.enabled, 'intelliIgnore.enabled');
validateBoolean(sanitizedIntelliIgnore.dynamic, 'intelliIgnore.dynamic');
validateBoolean(sanitizedIntelliIgnore.ignoreAds, 'intelliIgnore.ignoreAds');
validateBoolean(sanitizedIntelliIgnore.ignoreBanners, 'intelliIgnore.ignoreBanners');
validateBoolean(sanitizedIntelliIgnore.ignoreCarousels, 'intelliIgnore.ignoreCarousels');
validateBoolean(
sanitizedIntelliIgnore.ignoreCustomElementsEnabled,
'intelliIgnore.ignoreCustomElementsEnabled'
);
if (sanitizedIntelliIgnore.ignoreCustomElementsClasses != null &&
typeof sanitizedIntelliIgnore.ignoreCustomElementsClasses !== 'string') {
throw new Error(
"Invalid PERCY_VISUAL_CONFIG: 'intelliIgnore.ignoreCustomElementsClasses' must be a string"
);
}
validateBoolean(sanitizedIntelliIgnore.ignoreImages, 'intelliIgnore.ignoreImages');
validateNumberInRange(
sanitizedIntelliIgnore.diffIgnorePercentage,
'intelliIgnore.diffIgnorePercentage'
);
visualConfig.intelliIgnore = sanitizedIntelliIgnore;
}
return visualConfig;
}
// Validate project path arguments
function validateProjectPath(path) {
if (!path) throw new Error('Missing project path');
if (!/^[^/]+?\/.+/.test(path)) {
throw new Error(`Invalid project path. Expected "org/project" but received "${path}"`);
}
}
// PercyClient is used to communicate with the Percy API to create and finalize
// builds and snapshot. Uses @percy/env to collect environment information used
// during build creation.
export class PercyClient {
log = logger('client');
env = new PercyEnv(process.env);
clientInfo = new Set();
environmentInfo = new Set();
constructor({
// read or write token, defaults to PERCY_TOKEN environment variable
token,
// initial user agent info
clientInfo,
environmentInfo,
config,
labels,
// versioned api url
apiUrl = PERCY_CLIENT_API_URL
} = {}) {
Object.assign(this, { token, config: config || {}, apiUrl, labels: labels });
this.addClientInfo(clientInfo);
this.addEnvironmentInfo(environmentInfo);
this.buildType = null;
this.screenshotFlow = null;
}
// Adds additional unique client info.
addClientInfo(info) {
for (let i of [].concat(info)) {
if (i) this.clientInfo.add(i);
}
}
// Adds additional unique environment info.
addEnvironmentInfo(info) {
for (let i of [].concat(info)) {
if (i) this.environmentInfo.add(i);
}
}
// Stringifies client and environment info.
userAgent() {
// forcedPkgValue has been added since when percy package is bundled inside Electron app (LCNC)
// we can't read Percy's package json for package name and version, so we are passing it via env variables
if (this.env.forcedPkgValue) pkg = this.env.forcedPkgValue;
let client = new Set([`Percy/${/\w+$/.exec(this.apiUrl)}`]
.concat(`${pkg.name}/${pkg.version}`, ...this.clientInfo)
.filter(Boolean));
let environment = new Set([...this.environmentInfo]
.concat(`node/${process.version}`, this.env.info)
.filter(Boolean));
return `${[...client].join(' ')} (${[...environment].join('; ')})`;
}
// Checks for a Percy token and returns it.
// Priority order is
// 1. passed token to constructor
// 2. PERCY_TOKEN env var [ from env package ]
// 3. token from percy config
getToken(raiseIfMissing = true) {
let token = this.token || this.env.token || this.config.percy?.token;
if (!token && raiseIfMissing) throw new Error('Missing Percy token');
return token;
}
// Returns common headers used for each request with additional
// headers. Throws an error when the token is missing, which is a required
// authorization header.
headers(headers, raiseIfMissing = true) {
return Object.assign({
Authorization: `Token token=${this.getToken(raiseIfMissing)}`,
'User-Agent': this.userAgent()
}, headers);
}
// Performs a GET request for an API endpoint with appropriate headers.
// we create a copy of meta as we update it in request and we wont want those updates
// to go back to caller - should be only limited to current function
get(path, { ...meta } = {}) {
return logger.measure('client:get', meta.identifier, meta, () => {
return request(`${this.apiUrl}/${path}`, {
headers: this.headers(),
method: 'GET',
meta
});
});
}
// Performs a POST request to a JSON API endpoint with appropriate headers.
post(path, body = {}, { ...meta } = {}, customHeaders = {}, raiseIfMissing = true) {
return logger.measure('client:post', meta.identifier || 'Unknown', meta, () => {
return request(`${this.apiUrl}/${path}`, {
headers: this.headers({
'Content-Type': 'application/vnd.api+json',
...customHeaders
}, raiseIfMissing),
method: 'POST',
body,
meta
});
});
}
// Performs a PATCH request to a JSON API endpoint with appropriate headers.
patch(path, body = {}, { ...meta } = {}, customHeaders = {}, raiseIfMissing = true) {
return logger.measure('client:patch', meta.identifier || 'Unknown', meta, () => {
return request(`${this.apiUrl}/${path}`, {
headers: this.headers({
'Content-Type': 'application/vnd.api+json',
...customHeaders
}, raiseIfMissing),
method: 'PATCH',
body,
meta
});
});
}
// Creates a build with optional build resources. Only one build can be
// created at a time per instance so snapshots and build finalization can be
// done more seamlessly without manually tracking build ids
async createBuild({ resources = [], projectType, cliStartTime = null } = {}) {
this.log.debug('Creating a new build...');
let visualConfig = parseVisualConfigFromEnv(this.log);
let source = 'user_created';
if (process.env.PERCY_ORIGINATED_SOURCE) {
source = 'bstack_sdk_created';
} else if (process.env.PERCY_AUTO_ENABLED_GROUP_BUILD === 'true') {
source = 'auto_enabled_group';
}
let tagsArr = tagsList(this.labels);
// PER-9724: internal-only priority request. Set by internal product
// orchestration (e.g. Scanner / LCA) via PERCY_PRIORITY; mirrors the
// PERCY_ORIGINATED_SOURCE internal signal above. percy-api only honors this
// for eligible internal build types, so it is a no-op for customer builds.
let priority = process.env.PERCY_PRIORITY === 'true';
return this.post('builds', {
data: {
type: 'builds',
attributes: {
type: projectType,
branch: this.env.git.branch,
'target-branch': this.env.target.branch,
'target-commit-sha': this.env.target.commit,
'commit-sha': this.env.git.sha,
'commit-committed-at': this.env.git.committedAt,
'commit-author-name': this.env.git.authorName,
'commit-author-email': this.env.git.authorEmail,
'commit-committer-name': this.env.git.committerName,
'commit-committer-email': this.env.git.committerEmail,
'commit-message': this.env.git.message,
'pull-request-number': this.env.pullRequest,
'parallel-nonce': this.env.parallel.nonce,
'parallel-total-shards': this.env.parallel.total,
partial: this.env.partial,
tags: tagsArr,
'cli-start-time': cliStartTime,
source: source,
'skip-base-build': this.config.percy?.skipBaseBuild,
'testhub-build-uuid': this.env.testhubBuildUuid,
'testhub-build-run-id': this.env.testhubBuildRunId,
...(visualConfig ? { 'visual-config': visualConfig } : {}),
...(priority ? { priority: true } : {})
},
relationships: {
resources: {
data: resources.map(r => ({
type: 'resources',
id: r.sha || sha256hash(r.content),
attributes: {
'resource-url': r.url,
'is-root': r.root || null,
mimetype: r.mimetype || null
}
}))
}
}
}
});
}
// Finalizes the active build. When `all` is true, `all-shards=true` is
// added as a query param so the API finalizes all other build shards.
async finalizeBuild(buildId, { all = false } = {}) {
validateId('build', buildId);
let qs = all ? 'all-shards=true' : '';
this.log.debug(`Finalizing build ${buildId}...`);
return this.post(`builds/${buildId}/finalize?${qs}`, {}, { identifier: 'build.finalze' });
}
// Retrieves build data by id. Requires a read access token.
async getBuild(buildId) {
validateId('build', buildId);
this.log.debug(`Get build ${buildId}`);
return this.get(`builds/${buildId}`);
}
async getComparisonDetails(comparisonId) {
validateId('comparison', comparisonId);
try {
return await this.get(`comparisons/${comparisonId}?sync=true&response_format=sync-cli`);
} catch (error) {
this.log.error(error);
if (error.response.statusCode === 403) {
throw new Error(INVALID_TOKEN_ERROR_MESSAGE);
}
throw error;
}
}
async getSnapshotDetails(snapshotId) {
validateId('snapshot', snapshotId);
try {
return await this.get(`snapshots/${snapshotId}?sync=true&response_format=sync-cli`);
} catch (error) {
this.log.error(error);
if (error.response.statusCode === 403) {
throw new Error(INVALID_TOKEN_ERROR_MESSAGE);
}
throw error;
}
}
// Retrieves snapshot/comparison data by id. Requires a read access token.
async getStatus(type, ids) {
if (!['snapshot', 'comparison'].includes(type)) throw new Error('Invalid type passed');
this.log.debug(`Getting ${type} status for ids ${ids}`);
return this.get(`job_status?sync=true&type=${type}&id=${ids.join()}`);
}
// Returns device details enabled on project associated with given token
async getDeviceDetails(buildId) {
try {
let url = 'discovery/device-details';
if (buildId) url += `?build_id=${buildId}`;
const { data } = await this.get(url);
return data;
} catch (e) {
return [];
}
}
// Retrieves project builds optionally filtered. Requires a read access token.
async getBuilds(project, filters = {}) {
validateProjectPath(project);
let qs = Object.keys(filters).map(k => (
Array.isArray(filters[k])
? filters[k].map(v => `filter[${k}][]=${v}`).join('&')
: `filter[${k}]=${filters[k]}`
)).join('&');
this.log.debug(`Fetching builds for ${project}`);
return this.get(`projects/${project}/builds?${qs}`);
}
// Resolves when the build has finished and is no longer pending or
// processing. By default, will time out if no update after 10 minutes.
waitForBuild({
build,
project,
commit,
timeout = 10 * 60 * 1000,
interval = 10_000
}, onProgress) {
if (interval < MIN_POLLING_INTERVAL) {
this.log.warn(`Ignoring interval since it cannot be less than ${MIN_POLLING_INTERVAL}ms.`);
interval = MIN_POLLING_INTERVAL;
}
if (!project && commit) {
throw new Error('Missing project path for commit');
} else if (!project && !build) {
throw new Error('Missing project path or build ID');
} else if (project) {
validateProjectPath(project);
}
commit ||= this.env.git.sha;
if (!build && !commit) throw new Error('Missing build commit');
let sha = commit && (git(`rev-parse ${commit}`) || commit);
let fetchData = async () => build
? (await this.getBuild(build)).data
: (await this.getBuilds(project, { sha })).data?.[0];
this.log.debug(`Waiting for build ${build || `${project} (${commit})`}...`);
// recursively poll every second until the build finishes
return new Promise((resolve, reject) => (async function poll(last, t) {
try {
let data = await fetchData();
let state = data?.attributes.state;
let pending = !state || state === 'pending' || state === 'processing';
let updated = JSON.stringify(data) !== JSON.stringify(last);
// new data received
if (updated) {
t = Date.now();
// no new data within the timeout
} else if (Date.now() - t >= timeout) {
throw new Error(state == null ? 'Build not found' : 'Timeout exceeded with no updates');
}
// call progress every update after the first update
if ((last || pending) && updated) {
onProgress?.(data);
}
// not finished, poll again
if (pending) {
return setTimeout(poll, interval, data, t);
// build finished
} else {
// ensure progress is called at least once
if (!last) onProgress?.(data);
resolve({ data });
}
} catch (err) {
reject(err);
}
})(null, Date.now()));
}
// Uploads a single resource to the active build. If `filepath` is provided,
// `content` is read from the filesystem. The sha is optional and will be
// created from `content` if one is not provided.
async uploadResource(buildId, { url, sha, filepath, content } = {}, meta = {}) {
validateId('build', buildId);
if (filepath) {
content = await fs.promises.readFile(filepath);
if (process.env.PERCY_GZIP) {
content = Pako.gzip(content);
}
}
let encodedContent = base64encode(content);
this.log.debug(`Uploading ${formatBytes(encodedContent.length)} resource: ${url}`, meta);
this.mayBeLogUploadSize(encodedContent.length, meta);
return this.post(`builds/${buildId}/resources`, {
data: {
type: 'resources',
id: sha || sha256hash(content),
attributes: {
'base64-content': encodedContent
}
}
}, { identifier: 'resource.post', ...meta });
}
// Uploads resources to the active build concurrently, two at a time.
async uploadResources(buildId, resources, meta = {}) {
validateId('build', buildId);
this.log.debug(`Uploading resources for ${buildId}...`, meta);
const uploadConcurrency = parseInt(process.env.PERCY_RESOURCE_UPLOAD_CONCURRENCY) || 2;
return pool(function*() {
for (let resource of resources) {
let resourceMeta = {
url: resource.url,
sha: resource.sha,
...meta
};
yield this.uploadResource(buildId, resource, resourceMeta).then((result) => {
this.log.debug(`Uploaded resource ${resource.url}`, resourceMeta);
return result;
});
}
}, this, uploadConcurrency);
}
// Creates a snapshot for the active build using the provided attributes.
async createSnapshot(buildId, {
name,
widths,
scope,
scopeOptions,
minHeight,
enableJavaScript,
enableLayout,
clientInfo,
environmentInfo,
sync,
testCase,
labels,
thTestCaseExecutionId,
browsers,
regions,
algorithm,
algorithmConfiguration,
resources = [],
meta
} = {}) {
validateId('build', buildId);
this.addClientInfo(clientInfo);
this.addEnvironmentInfo(environmentInfo);
if (!this.clientInfo.size || !this.environmentInfo.size) {
this.log.warn('Warning: Missing `clientInfo` and/or `environmentInfo` properties', meta);
}
let tagsArr = tagsList(labels);
let regionsArr = makeRegions(regions, algorithm, algorithmConfiguration);
this.log.debug(`Validating resources: ${name}...`, meta);
for (let resource of resources) {
if (resource.sha || resource.content || !resource.filepath) continue;
resource.content = await fs.promises.readFile(resource.filepath);
}
this.log.debug(`Creating snapshot: ${name}...`, meta);
return this.post(`builds/${buildId}/snapshots`, {
data: {
type: 'snapshots',
attributes: {
name: name || null,
widths: widths || null,
scope: scope || null,
sync: !!sync,
'test-case': testCase || null,
tags: tagsArr,
'scope-options': scopeOptions || {},
regions: regionsArr || null,
'minimum-height': minHeight || null,
'enable-javascript': enableJavaScript || null,
'enable-layout': enableLayout || false,
'th-test-case-execution-id': thTestCaseExecutionId || null,
browsers: normalizeBrowsers(browsers) || null
},
relationships: {
resources: {
data: resources.map(r => ({
type: 'resources',
id: r.sha ?? (r.content && sha256hash(r.content)),
attributes: {
'resource-url': r.url || null,
'is-root': r.root || null,
'for-widths': r.widths || null,
mimetype: r.mimetype || null
}
}))
}
}
}
}, { identifier: 'snapshot.post', ...meta });
}
// Finalizes a snapshot.
async finalizeSnapshot(snapshotId, meta = {}) {
validateId('snapshot', snapshotId);
this.log.debug(`Finalizing snapshot ${snapshotId}...`, meta);
return this.post(`snapshots/${snapshotId}/finalize`, {}, { identifier: 'snapshot.finalze', ...meta });
}
// Convenience method for creating a snapshot for the active build, uploading
// missing resources for the snapshot, and finalizing the snapshot.
async sendSnapshot(buildId, options) {
let { meta = {} } = options;
let snapshot = await this.createSnapshot(buildId, options);
meta.snapshotId = snapshot.data.id;
let missing = snapshot.data.relationships?.['missing-resources']?.data;
this.log.debug(`${missing?.length || 0} Missing resources: ${options.name}...`, meta);
if (missing?.length) {
let resources = options.resources.reduce((acc, r) => Object.assign(acc, { [r.sha]: r }), {});
await this.uploadResources(buildId, missing.map(({ id }) => resources[id]), meta);
}
this.log.debug(`Resources uploaded: ${options.name}...`, meta);
await this.finalizeSnapshot(snapshot.data.id, meta);
this.log.debug(`Finalized snapshot: ${options.name}...`, meta);
return snapshot;
}
async createComparison(snapshotId, {
tag, tiles = [], externalDebugUrl, ignoredElementsData,
domInfoSha, consideredElementsData, elementSelectorsData, metadata, sync, regions, algorithm,
algorithmConfiguration, meta = {}
} = {}) {
validateId('snapshot', snapshotId);
// Remove post percy api deploy
this.log.debug(`Creating comparison: ${tag.name}...`, meta);
for (let tile of tiles) {
if (tile.sha) continue;
if (tile.content && typeof tile.content === 'string') {
// base64 encoded content coming from SDK
tile.content = Buffer.from(tile.content, 'base64');
} else if (tile.filepath) {
tile.content = await fs.promises.readFile(tile.filepath);
}
}
let regionsArr = makeRegions(regions, algorithm, algorithmConfiguration);
this.log.debug(`${tiles.length} tiles for comparison: ${tag.name}...`, meta);
return this.post(`snapshots/${snapshotId}/comparisons`, {
data: {
type: 'comparisons',
attributes: {
'external-debug-url': externalDebugUrl || null,
'ignore-elements-data': ignoredElementsData || null,
regions: regionsArr || null,
'consider-elements-data': consideredElementsData || null,
'element-selectors-data': elementSelectorsData || null,
'dom-info-sha': domInfoSha || null,
sync: !!sync,
metadata: metadata || null
},
relationships: {
tag: {
data: {
type: 'tag',
attributes: {
name: tag.name || null,
width: tag.width || null,
height: tag.height || null,
'os-name': tag.osName || null,
'os-version': tag.osVersion || null,
orientation: tag.orientation || null,
'browser-name': tag.browserName || null,
'browser-version': tag.browserVersion || null,
'percy-browser-custom-name': tag.percyBrowserCustomName || null,
resolution: tag.resolution || null
}
}
},
tiles: {
data: tiles.map(t => ({
type: 'tiles',
attributes: {
sha: t.sha || (t.content && sha256hash(t.content)),
'status-bar-height': t.statusBarHeight || null,
'nav-bar-height': t.navBarHeight || null,
'header-height': t.headerHeight || null,
'footer-height': t.footerHeight || null,
fullscreen: t.fullscreen || null
}
}))
}
}
}
}, { identifier: 'comparison.post', ...meta });
}
async uploadComparisonTile(comparisonId, { index = 0, total = 1, filepath, content, sha } = {}, meta = {}) {
validateId('comparison', comparisonId);
if (sha) {
return await this.verify(comparisonId, sha);
}
if (filepath && !content) content = await fs.promises.readFile(filepath);
let encodedContent = base64encode(content);
this.log.debug(`Uploading ${formatBytes(encodedContent.length)} comparison tile: ${index + 1}/${total} (${comparisonId})...`, meta);
this.mayBeLogUploadSize(encodedContent.length);
return this.post(`comparisons/${comparisonId}/tiles`, {
data: {
type: 'tiles',
attributes: {
'base64-content': encodedContent,
index
}
}
}, { identifier: 'comparison.tile.post', ...meta });
}
// Convenience method for verifying if tile is present
async verify(comparisonId, sha) {
let retries = 20;
let success = null;
do {
await waitForTimeout(500);
success = await this.verifyComparisonTile(comparisonId, sha);
retries -= 1;
}
while (retries > 0 && !success);
if (!success) {
let errMsg = 'Uploading comparison tile failed';
// Detecting error and logging fix for the same
// We are throwing this error as the comparison will be failed
// even if 1 tile gets failed
throw new Error(errMsg);
}
return true;
}
async verifyComparisonTile(comparisonId, sha, meta = {}) {
validateId('comparison', comparisonId);
this.log.debug(`Verifying comparison tile with sha: ${sha}`, meta);
try {
return await this.post(`comparisons/${comparisonId}/tiles/verify`, {
data: {
type: 'tiles',
attributes: {
sha: sha
}
}
}, { identifier: 'comparison.tile.verify', ...meta });
} catch (error) {
if (error.response.statusCode === 400) {
return false;
}
this.log.error(error);
throw error;
}
}
async uploadComparisonTiles(comparisonId, tiles) {
validateId('comparison', comparisonId);
this.log.debug(`Uploading comparison tiles for ${comparisonId}...`);
return pool(function*() {
for (let index = 0; index < tiles.length; index++) {
yield this.uploadComparisonTile(comparisonId, {
index, total: tiles.length, ...tiles[index]
});
}
}, this, 2);
}
async finalizeComparison(comparisonId, meta = {}) {
validateId('comparison', comparisonId);
this.log.debug(`Finalizing comparison ${comparisonId}...`);
return this.post(`comparisons/${comparisonId}/finalize`, {}, { identifier: 'comparison.finalize', ...meta });
}
async sendComparison(buildId, options) {
let { meta } = options;
if (!validateTiles(options.tiles)) {
throw new Error('sha, filepath or content should be present in tiles object');
}
let snapshot = await this.createSnapshot(buildId, options);
let comparison = await this.createComparison(snapshot.data.id, options);
await this.uploadComparisonTiles(comparison.data.id, options.tiles);
this.log.debug(`Created comparison: ${comparison.data.id} ${options.tag.name}`, meta);
await this.finalizeComparison(comparison.data.id);
this.log.debug(`Finalized comparison: ${comparison.data.id} ${options.tag.name}`, meta);
return comparison;
}
async sendBuildEvents(buildId, body, meta = {}, { eventName, category } = {}) {
validateId('build', buildId);
this.log.debug('Sending Build Events');
return this.post(`builds/${buildId}/send-events`, {
// newer params are optional; when omitted the API applies its defaults
...(eventName && { event_name: eventName }),
...(category && { category }),
data: body
}, { identifier: 'build.send_events', ...meta });
}
async sendBuildLogs(body, meta = {}) {
this.log.debug('Sending Build Logs', meta);
return this.post('logs', {
data: body
}, { identifier: 'build.send_logs', ...meta });
}
async getErrorAnalysis(errors, meta = {}) {
const errorLogs = formatLogErrors(errors);
this.log.debug('Sending error logs for analysis', meta);
return this.post('suggestions/from_logs', {
data: errorLogs
}, { identifier: 'error.analysis.get', ...meta });
}
// Performs a review action (approve, unapprove, reject) on a specific build.
// This function handles the common logic for sending review requests.
async reviewBuild(buildId, action, username, accessKey) {
validateId('build', buildId);
this.log.debug(`Sending ${action} action for build ${buildId}...`);
const requestBody = {
data: {
attributes: {
action: action
},
relationships: {
build: {
data: {
type: 'builds',
id: buildId
}
}
},
type: 'reviews'
}
};
// For the review action, we use accessKey and username in custom headers
// and do not require a project token.
return this.post(
'reviews',
requestBody,
{ identifier: `build.${action}` },
{ Authorization: `Basic ${base64encode(`${username}:${accessKey}`)}` },
false
);
}
async approveBuild(buildId, username, accessKey) {
return this.reviewBuild(buildId, 'approve', username, accessKey);
}
async unapproveBuild(buildId, username, accessKey) {
return this.reviewBuild(buildId, 'unapprove', username, accessKey);
}
async rejectBuild(buildId, username, accessKey) {
return this.reviewBuild(buildId, 'reject', username, accessKey);
}
async deleteBuild(buildId, username, accessKey) {
validateId('build', buildId);
this.log.debug(`Sending Delete action for build ${buildId}...`);
// For the delete action, we use accessKey and username in custom headers
// and do not require a project token.
return this.post(
`builds/${buildId}/delete`,
{},
{ identifier: 'build.delete' },
{ Authorization: `Basic ${base64encode(`${username}:${accessKey}`)}` },
false
);
}
// Updates project domain configuration
async updateProjectDomainConfig({ buildId, allowedDomains = [], errorDomains = [] } = {}) {
this.log.debug('Updating domain config');
// Authentication happens on Project Token so id is not used
return this.patch('project-domain-configs/cli-test-id', {
data: {
type: 'projects',
attributes: {
'domain-config': {
build_id: buildId,
allowed_domains: allowedDomains,
error_domains: errorDomains
}
}
}
}, { identifier: 'project.updateDomainConfig' });
}
// Gets project domain configuration including worker URL and allowed/blocked domains
async getProjectDomainConfig() {
this.log.debug('Fetching project domain config');
try {
// Authentication happens on Project Token so id is not used
const response = await this.get('project-domain-configs/cli-test-id');
const projectData = response?.data;
return {
workerUrl: projectData?.attributes?.['domain-validator-worker-url'] || null,
domainConfig: projectData?.attributes?.['domain-config'] || null
};
} catch (error) {
this.log.debug(`Failed to fetch project domain config: ${error.message}`);
return { workerUrl: null, domainConfig: null };
}
}
// Validates a domain with the Cloudflare worker endpoint
async validateDomain(url, options = {}) {
const { validationEndpoint, timeout = 5000 } = options;
if (!validationEndpoint) {
throw new Error('Domain validation endpoint URL is required');
}
this.log.debug(`Validating domain: ${url} via ${validationEndpoint}`);
try {
const response = await request(validationEndpoint, {
method: 'POST',
headers: this.headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({ url }),
timeout,
retries: 0 // Don't retry validation requests
});
return response;
} catch (error) {
this.log.debug(`Domain validation failed for ${url}: ${error.message}`);
throw error;
}
}
mayBeLogUploadSize(contentSize, meta = {}) {
if (contentSize >= 25 * 1024 * 1024) {