@flakiness/sdk 0.95.0

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.
@@ -0,0 +1,818 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/cmd-upload-playwright-json.ts
4
+ import fs3 from "fs/promises";
5
+ import path from "path";
6
+
7
+ // src/playwrightJSONReport.ts
8
+ import { FlakinessReport as FK, FlakinessReport } from "@flakiness/report";
9
+ import debug from "debug";
10
+ import { posix as posixPath2 } from "path";
11
+
12
+ // src/utils.ts
13
+ import assert from "assert";
14
+ import { spawnSync } from "child_process";
15
+ import crypto from "crypto";
16
+ import fs from "fs";
17
+ import http from "http";
18
+ import https from "https";
19
+ import os from "os";
20
+ import { posix as posixPath, win32 as win32Path } from "path";
21
+ import util from "util";
22
+ import zlib from "zlib";
23
+ var gzipAsync = util.promisify(zlib.gzip);
24
+ var gunzipAsync = util.promisify(zlib.gunzip);
25
+ var gunzipSync = zlib.gunzipSync;
26
+ var brotliCompressAsync = util.promisify(zlib.brotliCompress);
27
+ var brotliCompressSync = zlib.brotliCompressSync;
28
+ async function existsAsync(aPath) {
29
+ return fs.promises.stat(aPath).then(() => true).catch((e) => false);
30
+ }
31
+ function extractEnvConfiguration() {
32
+ const ENV_PREFIX = "FK_ENV_";
33
+ return Object.fromEntries(
34
+ Object.entries(process.env).filter(([key]) => key.toUpperCase().startsWith(ENV_PREFIX.toUpperCase())).map(([key, value]) => [key.substring(ENV_PREFIX.length).toLowerCase(), (value ?? "").trim().toLowerCase()])
35
+ );
36
+ }
37
+ function sha1File(filePath) {
38
+ return new Promise((resolve, reject) => {
39
+ const hash = crypto.createHash("sha1");
40
+ const stream = fs.createReadStream(filePath);
41
+ stream.on("data", (chunk) => {
42
+ hash.update(chunk);
43
+ });
44
+ stream.on("end", () => {
45
+ resolve(hash.digest("hex"));
46
+ });
47
+ stream.on("error", (err) => {
48
+ reject(err);
49
+ });
50
+ });
51
+ }
52
+ function sha1Buffer(data) {
53
+ const hash = crypto.createHash("sha1");
54
+ hash.update(data);
55
+ return hash.digest("hex");
56
+ }
57
+ async function retryWithBackoff(job, backoff = []) {
58
+ for (const timeout of backoff) {
59
+ try {
60
+ return await job();
61
+ } catch (e) {
62
+ if (e instanceof AggregateError)
63
+ console.error(`[flakiness.io err]`, e.errors[0].message);
64
+ else if (e instanceof Error)
65
+ console.error(`[flakiness.io err]`, e.message);
66
+ else
67
+ console.error(`[flakiness.io err]`, e);
68
+ await new Promise((x) => setTimeout(x, timeout));
69
+ }
70
+ }
71
+ return await job();
72
+ }
73
+ var httpUtils;
74
+ ((httpUtils2) => {
75
+ function createRequest({ url, method = "get", headers = {} }) {
76
+ let resolve;
77
+ let reject;
78
+ const responseDataPromise = new Promise((a, b) => {
79
+ resolve = a;
80
+ reject = b;
81
+ });
82
+ const protocol = url.startsWith("https") ? https : http;
83
+ const request = protocol.request(url, { method, headers }, (res) => {
84
+ const chunks = [];
85
+ res.on("data", (chunk) => chunks.push(chunk));
86
+ res.on("end", () => {
87
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
88
+ resolve(Buffer.concat(chunks));
89
+ else
90
+ reject(new Error(`Request to ${url} failed with ${res.statusCode}`));
91
+ });
92
+ res.on("error", (error) => reject(error));
93
+ });
94
+ request.on("error", reject);
95
+ return { request, responseDataPromise };
96
+ }
97
+ httpUtils2.createRequest = createRequest;
98
+ async function getBuffer(url, backoff) {
99
+ return await retryWithBackoff(async () => {
100
+ const { request, responseDataPromise } = createRequest({ url });
101
+ request.end();
102
+ return await responseDataPromise;
103
+ }, backoff);
104
+ }
105
+ httpUtils2.getBuffer = getBuffer;
106
+ async function getText(url, backoff) {
107
+ const buffer = await getBuffer(url, backoff);
108
+ return buffer.toString("utf-8");
109
+ }
110
+ httpUtils2.getText = getText;
111
+ async function getJSON(url) {
112
+ return JSON.parse(await getText(url));
113
+ }
114
+ httpUtils2.getJSON = getJSON;
115
+ async function postText(url, text, backoff) {
116
+ const headers = {
117
+ "Content-Type": "application/json",
118
+ "Content-Length": Buffer.byteLength(text) + ""
119
+ };
120
+ return await retryWithBackoff(async () => {
121
+ const { request, responseDataPromise } = createRequest({ url, headers, method: "post" });
122
+ request.write(text);
123
+ request.end();
124
+ return await responseDataPromise;
125
+ }, backoff);
126
+ }
127
+ httpUtils2.postText = postText;
128
+ async function postJSON(url, json, backoff) {
129
+ const buffer = await postText(url, JSON.stringify(json), backoff);
130
+ return JSON.parse(buffer.toString("utf-8"));
131
+ }
132
+ httpUtils2.postJSON = postJSON;
133
+ })(httpUtils || (httpUtils = {}));
134
+ var ansiRegex = new RegExp("[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", "g");
135
+ function stripAnsi(str) {
136
+ return str.replace(ansiRegex, "");
137
+ }
138
+ function shell(command, args, options) {
139
+ try {
140
+ const result = spawnSync(command, args, { encoding: "utf-8", ...options });
141
+ if (result.status !== 0) {
142
+ console.log(result);
143
+ console.log(options);
144
+ return void 0;
145
+ }
146
+ return result.stdout.trim();
147
+ } catch (e) {
148
+ console.log(e);
149
+ return void 0;
150
+ }
151
+ }
152
+ function readLinuxOSRelease() {
153
+ const osReleaseText = fs.readFileSync("/etc/os-release", "utf-8");
154
+ return new Map(osReleaseText.toLowerCase().split("\n").filter((line) => line.includes("=")).map((line) => {
155
+ line = line.trim();
156
+ let [key, value] = line.split("=");
157
+ if (value.startsWith('"') && value.endsWith('"'))
158
+ value = value.substring(1, value.length - 1);
159
+ return [key, value];
160
+ }));
161
+ }
162
+ function osLinuxInfo() {
163
+ const arch = shell(`uname`, [`-m`]);
164
+ const osReleaseMap = readLinuxOSRelease();
165
+ const name = osReleaseMap.get("name") ?? shell(`uname`);
166
+ const version = osReleaseMap.get("version_id");
167
+ return { name, arch, version };
168
+ }
169
+ function osDarwinInfo() {
170
+ const name = "macos";
171
+ const arch = shell(`uname`, [`-m`]);
172
+ const version = shell(`sw_vers`, [`-productVersion`]);
173
+ return { name, arch, version };
174
+ }
175
+ function osWinInfo() {
176
+ const name = "win";
177
+ const arch = process.arch;
178
+ const version = os.release();
179
+ return { name, arch, version };
180
+ }
181
+ function getOSInfo() {
182
+ if (process.platform === "darwin")
183
+ return osDarwinInfo();
184
+ if (process.platform === "win32")
185
+ return osWinInfo();
186
+ return osLinuxInfo();
187
+ }
188
+ function inferRunUrl() {
189
+ if (process.env.GITHUB_REPOSITORY && process.env.GITHUB_RUN_ID)
190
+ return `https://github.com/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
191
+ return void 0;
192
+ }
193
+ function parseStringDate(dateString) {
194
+ return +new Date(dateString);
195
+ }
196
+ function gitCommitInfo(gitRepo) {
197
+ const sha = shell(`git`, ["rev-parse", "HEAD"], {
198
+ cwd: gitRepo,
199
+ encoding: "utf-8"
200
+ });
201
+ assert(sha, `FAILED: git rev-parse HEAD @ ${gitRepo}`);
202
+ return sha.trim();
203
+ }
204
+ function computeGitRoot(somePathInsideGitRepo) {
205
+ const root = shell(`git`, ["rev-parse", "--show-toplevel"], {
206
+ cwd: somePathInsideGitRepo,
207
+ encoding: "utf-8"
208
+ });
209
+ assert(root, `FAILED: git rev-parse --show-toplevel HEAD @ ${somePathInsideGitRepo}`);
210
+ return normalizePath(root);
211
+ }
212
+ var IS_WIN32_PATH = new RegExp("^[a-zA-Z]:\\\\", "i");
213
+ var IS_ALMOST_POSIX_PATH = new RegExp("^[a-zA-Z]:/", "i");
214
+ function normalizePath(aPath) {
215
+ if (IS_WIN32_PATH.test(aPath)) {
216
+ aPath = aPath.split(win32Path.sep).join(posixPath.sep);
217
+ }
218
+ if (IS_ALMOST_POSIX_PATH.test(aPath))
219
+ return "/" + aPath[0] + aPath.substring(2);
220
+ return aPath;
221
+ }
222
+ function gitFilePath(gitRoot, absolutePath) {
223
+ return posixPath.relative(gitRoot, absolutePath);
224
+ }
225
+ function parseDurationMS(value) {
226
+ if (isNaN(value))
227
+ throw new Error("Duration cannot be NaN");
228
+ if (value < 0)
229
+ throw new Error(`Duration cannot be less than 0, found ${value}`);
230
+ return value | 0;
231
+ }
232
+ function createEnvironments(projects) {
233
+ const envConfiguration = extractEnvConfiguration();
234
+ const osInfo = getOSInfo();
235
+ let uniqueNames = /* @__PURE__ */ new Set();
236
+ const result = /* @__PURE__ */ new Map();
237
+ for (const project of projects) {
238
+ let defaultName = project.name;
239
+ if (!defaultName.trim())
240
+ defaultName = "anonymous";
241
+ let name = defaultName;
242
+ for (let i = 2; uniqueNames.has(name); ++i)
243
+ name = `${defaultName}-${i}`;
244
+ uniqueNames.add(defaultName);
245
+ result.set(project, {
246
+ name,
247
+ systemData: {
248
+ osArch: osInfo.arch,
249
+ osName: osInfo.name,
250
+ osVersion: osInfo.version
251
+ },
252
+ userSuppliedData: {
253
+ ...envConfiguration,
254
+ ...project.metadata
255
+ },
256
+ opaqueData: {
257
+ project
258
+ }
259
+ });
260
+ }
261
+ return result;
262
+ }
263
+
264
+ // src/playwrightJSONReport.ts
265
+ var dlog = debug("flakiness:json-report");
266
+ var PlaywrightJSONReport;
267
+ ((PlaywrightJSONReport2) => {
268
+ function collectMetadata(somePathInsideProject = process.cwd()) {
269
+ const commitId = gitCommitInfo(somePathInsideProject);
270
+ const osInfo = getOSInfo();
271
+ const metadata = {
272
+ gitRoot: computeGitRoot(somePathInsideProject),
273
+ commitId,
274
+ osName: osInfo.name,
275
+ arch: osInfo.arch,
276
+ osVersion: osInfo.version,
277
+ runURL: inferRunUrl()
278
+ };
279
+ dlog(`metadata directory: ${somePathInsideProject}`);
280
+ dlog(`metadata: ${JSON.stringify(metadata)}`);
281
+ dlog(`commit info: ${JSON.stringify(commitId)}`);
282
+ dlog(`os info: ${JSON.stringify(osInfo)}`);
283
+ return metadata;
284
+ }
285
+ PlaywrightJSONReport2.collectMetadata = collectMetadata;
286
+ async function parse(metadata, jsonReport, options) {
287
+ const context = {
288
+ projectId2environmentIdx: /* @__PURE__ */ new Map(),
289
+ testBaseDir: normalizePath(jsonReport.config.rootDir),
290
+ gitRoot: metadata.gitRoot,
291
+ attachments: /* @__PURE__ */ new Map(),
292
+ unaccessibleAttachmentPaths: [],
293
+ extractAttachments: options.extractAttachments
294
+ };
295
+ const configPath = jsonReport.config.configFile ? gitFilePath(context.gitRoot, normalizePath(jsonReport.config.configFile)) : void 0;
296
+ const report = {
297
+ category: FlakinessReport.CATEGORY_PLAYWRIGHT,
298
+ commitId: metadata.commitId,
299
+ configPath,
300
+ url: metadata.runURL,
301
+ environments: [],
302
+ suites: [],
303
+ opaqueData: jsonReport.config,
304
+ unattributedErrors: jsonReport.errors.map((error) => parseJSONError(context, error)),
305
+ // The report.stats is a releatively new addition to Playwright's JSONReport,
306
+ // so we have to polyfill with some reasonable values when it's missing.
307
+ duration: jsonReport.stats?.duration && jsonReport.stats?.duration > 0 ? parseDurationMS(jsonReport.stats.duration) : 0,
308
+ startTimestamp: jsonReport.stats && jsonReport.stats.startTime ? parseStringDate(jsonReport.stats.startTime) : Date.now()
309
+ };
310
+ report.environments = [...createEnvironments(jsonReport.config.projects).values()];
311
+ for (let envIdx = 0; envIdx < report.environments.length; ++envIdx)
312
+ context.projectId2environmentIdx.set(jsonReport.config.projects[envIdx].id, envIdx);
313
+ report.suites = await Promise.all(jsonReport.suites.map((suite) => parseJSONSuite(context, suite)));
314
+ return {
315
+ report: FK.dedupeSuitesTestsEnvironments(report),
316
+ attachments: [...context.attachments.values()],
317
+ unaccessibleAttachmentPaths: context.unaccessibleAttachmentPaths
318
+ };
319
+ }
320
+ PlaywrightJSONReport2.parse = parse;
321
+ })(PlaywrightJSONReport || (PlaywrightJSONReport = {}));
322
+ async function parseJSONSuite(context, jsonSuite) {
323
+ let type = "suite";
324
+ if (jsonSuite.column === 0 && jsonSuite.line === 0)
325
+ type = "file";
326
+ else if (!jsonSuite.title)
327
+ type = "anonymous suite";
328
+ const suite = {
329
+ type,
330
+ title: jsonSuite.title,
331
+ location: {
332
+ file: gitFilePath(context.gitRoot, normalizePath(jsonSuite.file)),
333
+ line: jsonSuite.line,
334
+ column: jsonSuite.column
335
+ }
336
+ };
337
+ if (jsonSuite.suites && jsonSuite.suites.length)
338
+ suite.suites = await Promise.all(jsonSuite.suites.map((suite2) => parseJSONSuite(context, suite2)));
339
+ if (jsonSuite.specs && jsonSuite.specs.length)
340
+ suite.tests = await Promise.all(jsonSuite.specs.map((spec) => parseJSONSpec(context, spec)));
341
+ return suite;
342
+ }
343
+ async function parseJSONSpec(context, jsonSpec) {
344
+ const test = {
345
+ title: jsonSpec.title,
346
+ tags: jsonSpec.tags,
347
+ location: {
348
+ file: gitFilePath(context.gitRoot, normalizePath(posixPath2.join(context.testBaseDir, normalizePath(jsonSpec.file)))),
349
+ line: jsonSpec.line,
350
+ column: jsonSpec.column
351
+ },
352
+ attempts: []
353
+ };
354
+ for (const jsonTest of jsonSpec.tests) {
355
+ const environmentIdx = context.projectId2environmentIdx.get(jsonTest.projectId);
356
+ if (environmentIdx === void 0)
357
+ throw new Error("Inconsistent report - no project for a test found!");
358
+ const testResults = jsonTest.results.filter((result) => result.status !== void 0);
359
+ if (!testResults.length)
360
+ continue;
361
+ test.attempts.push(...await Promise.all(testResults.map((jsonTestResult) => parseJSONTestResult(context, jsonTest, environmentIdx, jsonTestResult))));
362
+ }
363
+ return test;
364
+ }
365
+ function createLocation(context, location) {
366
+ return {
367
+ file: gitFilePath(context.gitRoot, normalizePath(location.file)),
368
+ line: location.line,
369
+ column: location.column
370
+ };
371
+ }
372
+ async function parseJSONTestResult(context, jsonTest, environmentIdx, jsonTestResult) {
373
+ const attachments = [];
374
+ const attempt = {
375
+ timeout: parseDurationMS(jsonTest.timeout),
376
+ annotations: jsonTest.annotations.map((annotation) => ({
377
+ type: annotation.type,
378
+ description: annotation.description,
379
+ location: annotation.location ? createLocation(context, annotation.location) : void 0
380
+ })),
381
+ environmentIdx,
382
+ expectedStatus: jsonTest.expectedStatus,
383
+ parallelIndex: jsonTestResult.parallelIndex,
384
+ status: jsonTestResult.status,
385
+ errors: jsonTestResult.errors && jsonTestResult.errors.length ? jsonTestResult.errors.map((error) => parseJSONError(context, error)) : void 0,
386
+ stdout: jsonTestResult.stdout && jsonTestResult.stdout.length ? jsonTestResult.stdout : void 0,
387
+ stderr: jsonTestResult.stderr && jsonTestResult.stderr.length ? jsonTestResult.stderr : void 0,
388
+ steps: jsonTestResult.steps ? jsonTestResult.steps.map((jsonTestStep) => parseJSONTestStep(context, jsonTestStep)) : void 0,
389
+ startTimestamp: parseStringDate(jsonTestResult.startTime),
390
+ duration: jsonTestResult.duration && jsonTestResult.duration > 0 ? parseDurationMS(jsonTestResult.duration) : 0,
391
+ attachments
392
+ };
393
+ if (context.extractAttachments) {
394
+ await Promise.all((jsonTestResult.attachments ?? []).map(async (jsonAttachment) => {
395
+ if (jsonAttachment.path && !await existsAsync(jsonAttachment.path)) {
396
+ context.unaccessibleAttachmentPaths.push(jsonAttachment.path);
397
+ return;
398
+ }
399
+ const id = jsonAttachment.path ? await sha1File(jsonAttachment.path) : sha1Buffer(jsonAttachment.body ?? "");
400
+ context.attachments.set(id, {
401
+ contentType: jsonAttachment.contentType,
402
+ id,
403
+ body: jsonAttachment.body ? Buffer.from(jsonAttachment.body) : void 0,
404
+ path: jsonAttachment.path
405
+ });
406
+ attachments.push({
407
+ id,
408
+ name: jsonAttachment.name,
409
+ contentType: jsonAttachment.contentType
410
+ });
411
+ }));
412
+ }
413
+ return attempt;
414
+ }
415
+ function parseJSONTestStep(context, jsonStep) {
416
+ const step = {
417
+ // NOTE: jsonStep.duration was -1 in some playwright versions
418
+ duration: parseDurationMS(Math.max(jsonStep.duration, 0)),
419
+ title: jsonStep.title
420
+ };
421
+ if (jsonStep.error)
422
+ step.error = parseJSONError(context, jsonStep.error);
423
+ if (jsonStep.steps)
424
+ step.steps = jsonStep.steps.map((childJSONStep) => parseJSONTestStep(context, childJSONStep));
425
+ return step;
426
+ }
427
+ function parseJSONError(context, error) {
428
+ return {
429
+ location: error.location ? createLocation(context, error.location) : void 0,
430
+ message: error.message ? stripAnsi(error.message).split("\n")[0] : void 0,
431
+ stack: error.stack,
432
+ value: error.value
433
+ };
434
+ }
435
+
436
+ // src/reportUploader.ts
437
+ import fs2 from "fs";
438
+ import { URL as URL2 } from "url";
439
+ import { brotliCompressSync as brotliCompressSync2 } from "zlib";
440
+
441
+ // ../server/lib/common/typedHttp.js
442
+ var TypedHTTP;
443
+ ((TypedHTTP2) => {
444
+ TypedHTTP2.StatusCodes = {
445
+ Informational: {
446
+ CONTINUE: 100,
447
+ SWITCHING_PROTOCOLS: 101,
448
+ PROCESSING: 102,
449
+ EARLY_HINTS: 103
450
+ },
451
+ Success: {
452
+ OK: 200,
453
+ CREATED: 201,
454
+ ACCEPTED: 202,
455
+ NON_AUTHORITATIVE_INFORMATION: 203,
456
+ NO_CONTENT: 204,
457
+ RESET_CONTENT: 205,
458
+ PARTIAL_CONTENT: 206,
459
+ MULTI_STATUS: 207
460
+ },
461
+ Redirection: {
462
+ MULTIPLE_CHOICES: 300,
463
+ MOVED_PERMANENTLY: 301,
464
+ MOVED_TEMPORARILY: 302,
465
+ SEE_OTHER: 303,
466
+ NOT_MODIFIED: 304,
467
+ USE_PROXY: 305,
468
+ TEMPORARY_REDIRECT: 307,
469
+ PERMANENT_REDIRECT: 308
470
+ },
471
+ ClientErrors: {
472
+ BAD_REQUEST: 400,
473
+ UNAUTHORIZED: 401,
474
+ PAYMENT_REQUIRED: 402,
475
+ FORBIDDEN: 403,
476
+ NOT_FOUND: 404,
477
+ METHOD_NOT_ALLOWED: 405,
478
+ NOT_ACCEPTABLE: 406,
479
+ PROXY_AUTHENTICATION_REQUIRED: 407,
480
+ REQUEST_TIMEOUT: 408,
481
+ CONFLICT: 409,
482
+ GONE: 410,
483
+ LENGTH_REQUIRED: 411,
484
+ PRECONDITION_FAILED: 412,
485
+ REQUEST_TOO_LONG: 413,
486
+ REQUEST_URI_TOO_LONG: 414,
487
+ UNSUPPORTED_MEDIA_TYPE: 415,
488
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416,
489
+ EXPECTATION_FAILED: 417,
490
+ IM_A_TEAPOT: 418,
491
+ INSUFFICIENT_SPACE_ON_RESOURCE: 419,
492
+ METHOD_FAILURE: 420,
493
+ MISDIRECTED_REQUEST: 421,
494
+ UNPROCESSABLE_ENTITY: 422,
495
+ LOCKED: 423,
496
+ FAILED_DEPENDENCY: 424,
497
+ UPGRADE_REQUIRED: 426,
498
+ PRECONDITION_REQUIRED: 428,
499
+ TOO_MANY_REQUESTS: 429,
500
+ REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
501
+ UNAVAILABLE_FOR_LEGAL_REASONS: 451
502
+ },
503
+ ServerErrors: {
504
+ INTERNAL_SERVER_ERROR: 500,
505
+ NOT_IMPLEMENTED: 501,
506
+ BAD_GATEWAY: 502,
507
+ SERVICE_UNAVAILABLE: 503,
508
+ GATEWAY_TIMEOUT: 504,
509
+ HTTP_VERSION_NOT_SUPPORTED: 505,
510
+ INSUFFICIENT_STORAGE: 507,
511
+ NETWORK_AUTHENTICATION_REQUIRED: 511
512
+ }
513
+ };
514
+ const AllErrorCodes = {
515
+ ...TypedHTTP2.StatusCodes.ClientErrors,
516
+ ...TypedHTTP2.StatusCodes.ServerErrors
517
+ };
518
+ class HttpError extends Error {
519
+ constructor(status, message) {
520
+ super(message);
521
+ this.status = status;
522
+ }
523
+ static withCode(code, message) {
524
+ const statusCode = AllErrorCodes[code];
525
+ const defaultMessage = code.split("_").map((word) => word.charAt(0) + word.slice(1).toLowerCase()).join(" ");
526
+ return new HttpError(statusCode, message ?? defaultMessage);
527
+ }
528
+ }
529
+ TypedHTTP2.HttpError = HttpError;
530
+ function isInformationalResponse(response) {
531
+ return response.status >= 100 && response.status < 200;
532
+ }
533
+ TypedHTTP2.isInformationalResponse = isInformationalResponse;
534
+ function isSuccessResponse(response) {
535
+ return response.status >= 200 && response.status < 300;
536
+ }
537
+ TypedHTTP2.isSuccessResponse = isSuccessResponse;
538
+ function isRedirectResponse(response) {
539
+ return response.status >= 300 && response.status < 400;
540
+ }
541
+ TypedHTTP2.isRedirectResponse = isRedirectResponse;
542
+ function isErrorResponse(response) {
543
+ return response.status >= 400 && response.status < 600;
544
+ }
545
+ TypedHTTP2.isErrorResponse = isErrorResponse;
546
+ function info(status) {
547
+ return { status };
548
+ }
549
+ TypedHTTP2.info = info;
550
+ function ok(data, status) {
551
+ return {
552
+ status: status ?? TypedHTTP2.StatusCodes.Success.OK,
553
+ data
554
+ };
555
+ }
556
+ TypedHTTP2.ok = ok;
557
+ function redirect(url, status = 302) {
558
+ return { status, url };
559
+ }
560
+ TypedHTTP2.redirect = redirect;
561
+ function error(message, status = TypedHTTP2.StatusCodes.ServerErrors.INTERNAL_SERVER_ERROR) {
562
+ return { status, message };
563
+ }
564
+ TypedHTTP2.error = error;
565
+ class Router {
566
+ constructor(_resolveContext) {
567
+ this._resolveContext = _resolveContext;
568
+ }
569
+ static create() {
570
+ return new Router(async (e) => e.ctx);
571
+ }
572
+ rawMethod(method, route) {
573
+ return {
574
+ [method]: {
575
+ method,
576
+ input: route.input,
577
+ etag: route.etag,
578
+ resolveContext: this._resolveContext,
579
+ handler: route.handler
580
+ }
581
+ };
582
+ }
583
+ get(route) {
584
+ return this.rawMethod("GET", {
585
+ ...route,
586
+ handler: (...args) => Promise.resolve(route.handler(...args)).then((result) => TypedHTTP2.ok(result))
587
+ });
588
+ }
589
+ post(route) {
590
+ return this.rawMethod("POST", {
591
+ ...route,
592
+ handler: (...args) => Promise.resolve(route.handler(...args)).then((result) => TypedHTTP2.ok(result))
593
+ });
594
+ }
595
+ use(resolveContext) {
596
+ return new Router(async (options) => {
597
+ const m = await this._resolveContext(options);
598
+ return resolveContext({ ...options, ctx: m });
599
+ });
600
+ }
601
+ }
602
+ TypedHTTP2.Router = Router;
603
+ function createClient(base, fetchCallback) {
604
+ function buildUrl(path2, input, options) {
605
+ const method = path2.at(-1);
606
+ const url = new URL(path2.slice(0, path2.length - 1).join("/"), base);
607
+ const signal = options?.signal;
608
+ let body = void 0;
609
+ if (method === "GET" && input)
610
+ url.searchParams.set("input", JSON.stringify(input));
611
+ else if (method !== "GET" && input)
612
+ body = JSON.stringify(input);
613
+ return {
614
+ url,
615
+ method,
616
+ headers: body ? { "Content-Type": "application/json" } : void 0,
617
+ body,
618
+ signal
619
+ };
620
+ }
621
+ function createProxy(path2 = []) {
622
+ return new Proxy(() => {
623
+ }, {
624
+ get(target, prop) {
625
+ if (typeof prop === "symbol")
626
+ return void 0;
627
+ if (prop === "prepare")
628
+ return (input, options) => buildUrl(path2, input, options);
629
+ const newPath = [...path2, prop];
630
+ return createProxy(newPath);
631
+ },
632
+ apply(target, thisArg, args) {
633
+ const options = buildUrl(path2, args[0], args[1]);
634
+ return fetchCallback(options.url, {
635
+ method: options.method,
636
+ body: options.body,
637
+ headers: options.headers,
638
+ signal: options.signal
639
+ }).then(async (response) => {
640
+ if (response.status >= 200 && response.status < 300) {
641
+ if (response.headers.get("content-type")?.includes("application/json")) {
642
+ const text = await response.text();
643
+ return text.length ? JSON.parse(text) : void 0;
644
+ }
645
+ return await response.blob();
646
+ }
647
+ if (response.status >= 400 && response.status < 600) {
648
+ const text = await response.text();
649
+ if (text)
650
+ throw new Error(`HTTP request failed with status ${response.status}: ${text}`);
651
+ else
652
+ throw new Error(`HTTP request failed with status ${response.status}`);
653
+ }
654
+ });
655
+ }
656
+ });
657
+ }
658
+ return createProxy();
659
+ }
660
+ TypedHTTP2.createClient = createClient;
661
+ })(TypedHTTP || (TypedHTTP = {}));
662
+
663
+ // src/serverapi.ts
664
+ function createServerAPI(endpoint, options) {
665
+ endpoint += "/api/";
666
+ const fetcher = options?.auth ? (url, init) => fetch(url, {
667
+ ...init,
668
+ headers: {
669
+ ...init.headers,
670
+ "Authorization": `Bearer ${options.auth}`
671
+ }
672
+ }) : fetch;
673
+ if (options?.retries)
674
+ return TypedHTTP.createClient(endpoint, (url, init) => retryWithBackoff(() => fetcher(url, init), options.retries));
675
+ return TypedHTTP.createClient(endpoint, fetcher);
676
+ }
677
+
678
+ // src/reportUploader.ts
679
+ var ReportUploader = class _ReportUploader {
680
+ static optionsFromEnv(overrides) {
681
+ const flakinessAccessToken = overrides?.flakinessAccessToken ?? process.env["FLAKINESS_ACCESS_TOKEN"];
682
+ if (!flakinessAccessToken)
683
+ return void 0;
684
+ const flakinessEndpoint = overrides?.flakinessEndpoint ?? process.env["FLAKINESS_ENDPOINT"] ?? "https://flakiness.io";
685
+ return { flakinessAccessToken, flakinessEndpoint };
686
+ }
687
+ static async upload(options) {
688
+ const uploaderOptions = _ReportUploader.optionsFromEnv(options);
689
+ if (!uploaderOptions) {
690
+ options.log?.(`[flakiness.io] Uploading skipped since no FLAKINESS_ACCESS_TOKEN is specified`);
691
+ return void 0;
692
+ }
693
+ const uploader = new _ReportUploader(uploaderOptions);
694
+ const upload = uploader.createUpload(options.report, options.attachments);
695
+ const uploadResult = await upload.upload();
696
+ if (!uploadResult.success) {
697
+ options.log?.(`[flakiness.io] X Failed to upload to ${uploaderOptions.flakinessEndpoint}: ${uploadResult.message}`);
698
+ return { errorMessage: uploadResult.message };
699
+ }
700
+ options.log?.(`[flakiness.io] \u2713 Report uploaded ${uploadResult.message ?? ""}`);
701
+ if (uploadResult.reportUrl)
702
+ options.log?.(`[flakiness.io] ${uploadResult.reportUrl}`);
703
+ }
704
+ _options;
705
+ constructor(options) {
706
+ this._options = options;
707
+ }
708
+ createUpload(report, attachments) {
709
+ const upload = new ReportUpload(this._options, report, attachments);
710
+ return upload;
711
+ }
712
+ };
713
+ var HTTP_BACKOFF = [100, 500, 1e3, 1e3, 1e3, 1e3];
714
+ var ReportUpload = class {
715
+ _report;
716
+ _attachments;
717
+ _options;
718
+ _api;
719
+ constructor(options, report, attachments) {
720
+ this._options = options;
721
+ this._report = report;
722
+ this._attachments = attachments;
723
+ this._api = createServerAPI(this._options.flakinessEndpoint, { retries: HTTP_BACKOFF });
724
+ }
725
+ async upload(options) {
726
+ const response = await this._api.run.startUpload.POST({
727
+ flakinessAccessToken: this._options.flakinessAccessToken,
728
+ attachmentIds: this._attachments.map((attachment) => attachment.id)
729
+ }).then((result) => ({ result, error: void 0 })).catch((e) => ({ result: void 0, error: e }));
730
+ if (response?.error || !response.result)
731
+ return { success: false, message: `flakiness.io returned error: ${response.error.message}` };
732
+ await Promise.all([
733
+ this._uploadReport(JSON.stringify(this._report), response.result.report_upload_url, options?.syncCompression ?? false),
734
+ ...this._attachments.map((attachment) => {
735
+ const uploadURL = response.result.attachment_upload_urls[attachment.id];
736
+ if (!uploadURL)
737
+ throw new Error("Internal error: missing upload URL for attachment!");
738
+ return this._uploadAttachment(attachment, uploadURL);
739
+ })
740
+ ]);
741
+ const response2 = await this._api.run.completeUpload.POST({
742
+ upload_token: response.result.upload_token
743
+ }).then((result) => ({ result, error: void 0 })).catch((e) => ({ error: e, result: void 0 }));
744
+ const url = response2?.result?.report_url ? new URL2(response2?.result.report_url, this._options.flakinessEndpoint).toString() : void 0;
745
+ return { success: true, reportUrl: url };
746
+ }
747
+ async _uploadReport(data, uploadUrl, syncCompression) {
748
+ const compressed = syncCompression ? brotliCompressSync2(data) : await brotliCompressAsync(data);
749
+ const headers = {
750
+ "Content-Type": "application/json",
751
+ "Content-Length": Buffer.byteLength(compressed) + "",
752
+ "Content-Encoding": "br"
753
+ };
754
+ await retryWithBackoff(async () => {
755
+ const { request, responseDataPromise } = httpUtils.createRequest({
756
+ url: uploadUrl,
757
+ headers,
758
+ method: "put"
759
+ });
760
+ request.write(compressed);
761
+ request.end();
762
+ await responseDataPromise;
763
+ }, HTTP_BACKOFF);
764
+ }
765
+ async _uploadAttachment(attachment, uploadUrl) {
766
+ const bytesLength = attachment.path ? (await fs2.promises.stat(attachment.path)).size : attachment.body ? Buffer.byteLength(attachment.body) : 0;
767
+ const headers = {
768
+ "Content-Type": attachment.contentType,
769
+ "Content-Length": bytesLength + ""
770
+ };
771
+ await retryWithBackoff(async () => {
772
+ const { request, responseDataPromise } = httpUtils.createRequest({
773
+ url: uploadUrl,
774
+ headers,
775
+ method: "put"
776
+ });
777
+ if (attachment.path) {
778
+ fs2.createReadStream(attachment.path).pipe(request);
779
+ } else {
780
+ if (attachment.body)
781
+ request.write(attachment.body);
782
+ request.end();
783
+ }
784
+ await responseDataPromise;
785
+ }, HTTP_BACKOFF);
786
+ }
787
+ };
788
+
789
+ // src/cli/cmd-upload-playwright-json.ts
790
+ async function cmdUploadPlaywrightJson(relativePath, options) {
791
+ const fullPath = path.resolve(relativePath);
792
+ if (!await fs3.access(fullPath, fs3.constants.F_OK).then(() => true).catch(() => false)) {
793
+ console.error(`Error: path ${fullPath} is not accessible`);
794
+ process.exit(1);
795
+ }
796
+ const text = await fs3.readFile(fullPath, "utf-8");
797
+ const playwrightJson = JSON.parse(text);
798
+ const { attachments, report, unaccessibleAttachmentPaths } = await PlaywrightJSONReport.parse(PlaywrightJSONReport.collectMetadata(), playwrightJson, {
799
+ extractAttachments: true
800
+ });
801
+ for (const unaccessibleAttachment of unaccessibleAttachmentPaths)
802
+ console.warn(`WARN: cannot access attachment ${unaccessibleAttachment}`);
803
+ const uploader = new ReportUploader({
804
+ flakinessAccessToken: options.accessToken,
805
+ flakinessEndpoint: options.endpoint
806
+ });
807
+ const upload = uploader.createUpload(report, attachments);
808
+ const uploadResult = await upload.upload();
809
+ if (!uploadResult.success) {
810
+ console.log(`[flakiness.io] X Failed to upload to ${options.endpoint}: ${uploadResult.message}`);
811
+ } else {
812
+ console.log(`[flakiness.io] \u2713 Report uploaded ${uploadResult.reportUrl ?? uploadResult.message ?? ""}`);
813
+ }
814
+ }
815
+ export {
816
+ cmdUploadPlaywrightJson
817
+ };
818
+ //# sourceMappingURL=cmd-upload-playwright-json.js.map