@flakiness/sdk 0.145.0 → 0.146.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.
@@ -1,321 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/cli/cmd-upload.ts
4
- import chalk from "chalk";
5
- import fs3 from "fs/promises";
6
- import path2 from "path";
7
-
8
- // src/reportUploader.ts
9
- import { compressTextAsync, compressTextSync } from "@flakiness/shared/node/compression.js";
10
- import assert from "assert";
11
- import fs2 from "fs";
12
- import { URL } from "url";
13
-
14
- // src/serverapi.ts
15
- import { TypedHTTP } from "@flakiness/shared/common/typedHttp.js";
16
-
17
- // src/utils.ts
18
- import { ReportUtils } from "@flakiness/report";
19
- import fs from "fs";
20
- import http from "http";
21
- import https from "https";
22
- import path, { posix as posixPath, win32 as win32Path } from "path";
23
- var FLAKINESS_DBG = !!process.env.FLAKINESS_DBG;
24
- function errorText(error) {
25
- return FLAKINESS_DBG ? error.stack : error.message;
26
- }
27
- async function retryWithBackoff(job, backoff = []) {
28
- for (const timeout of backoff) {
29
- try {
30
- return await job();
31
- } catch (e) {
32
- if (e instanceof AggregateError)
33
- console.error(`[flakiness.io err]`, errorText(e.errors[0]));
34
- else if (e instanceof Error)
35
- console.error(`[flakiness.io err]`, errorText(e));
36
- else
37
- console.error(`[flakiness.io err]`, e);
38
- await new Promise((x) => setTimeout(x, timeout));
39
- }
40
- }
41
- return await job();
42
- }
43
- var httpUtils;
44
- ((httpUtils2) => {
45
- function createRequest({ url, method = "get", headers = {} }) {
46
- let resolve;
47
- let reject;
48
- const responseDataPromise = new Promise((a, b) => {
49
- resolve = a;
50
- reject = b;
51
- });
52
- const protocol = url.startsWith("https") ? https : http;
53
- headers = Object.fromEntries(Object.entries(headers).filter(([key, value]) => value !== void 0));
54
- const request = protocol.request(url, { method, headers }, (res) => {
55
- const chunks = [];
56
- res.on("data", (chunk) => chunks.push(chunk));
57
- res.on("end", () => {
58
- if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
59
- resolve(Buffer.concat(chunks));
60
- else
61
- reject(new Error(`Request to ${url} failed with ${res.statusCode}`));
62
- });
63
- res.on("error", (error) => reject(error));
64
- });
65
- request.on("error", reject);
66
- return { request, responseDataPromise };
67
- }
68
- httpUtils2.createRequest = createRequest;
69
- async function getBuffer(url, backoff) {
70
- return await retryWithBackoff(async () => {
71
- const { request, responseDataPromise } = createRequest({ url });
72
- request.end();
73
- return await responseDataPromise;
74
- }, backoff);
75
- }
76
- httpUtils2.getBuffer = getBuffer;
77
- async function getText(url, backoff) {
78
- const buffer = await getBuffer(url, backoff);
79
- return buffer.toString("utf-8");
80
- }
81
- httpUtils2.getText = getText;
82
- async function getJSON(url) {
83
- return JSON.parse(await getText(url));
84
- }
85
- httpUtils2.getJSON = getJSON;
86
- async function postText(url, text, backoff) {
87
- const headers = {
88
- "Content-Type": "application/json",
89
- "Content-Length": Buffer.byteLength(text) + ""
90
- };
91
- return await retryWithBackoff(async () => {
92
- const { request, responseDataPromise } = createRequest({ url, headers, method: "post" });
93
- request.write(text);
94
- request.end();
95
- return await responseDataPromise;
96
- }, backoff);
97
- }
98
- httpUtils2.postText = postText;
99
- async function postJSON(url, json, backoff) {
100
- const buffer = await postText(url, JSON.stringify(json), backoff);
101
- return JSON.parse(buffer.toString("utf-8"));
102
- }
103
- httpUtils2.postJSON = postJSON;
104
- })(httpUtils || (httpUtils = {}));
105
- 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");
106
- async function resolveAttachmentPaths(report, attachmentsDir) {
107
- const attachmentFiles = await listFilesRecursively(attachmentsDir);
108
- const filenameToPath = new Map(attachmentFiles.map((file) => [path.basename(file), file]));
109
- const attachmentIdToPath = /* @__PURE__ */ new Map();
110
- const missingAttachments = /* @__PURE__ */ new Set();
111
- ReportUtils.visitTests(report, (test) => {
112
- for (const attempt of test.attempts) {
113
- for (const attachment of attempt.attachments ?? []) {
114
- const attachmentPath = filenameToPath.get(attachment.id);
115
- if (!attachmentPath) {
116
- missingAttachments.add(attachment.id);
117
- } else {
118
- attachmentIdToPath.set(attachment.id, {
119
- contentType: attachment.contentType,
120
- id: attachment.id,
121
- path: attachmentPath
122
- });
123
- }
124
- }
125
- }
126
- });
127
- return { attachmentIdToPath, missingAttachments: Array.from(missingAttachments) };
128
- }
129
- async function listFilesRecursively(dir, result = []) {
130
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
131
- for (const entry of entries) {
132
- const fullPath = path.join(dir, entry.name);
133
- if (entry.isDirectory())
134
- await listFilesRecursively(fullPath, result);
135
- else
136
- result.push(fullPath);
137
- }
138
- return result;
139
- }
140
- var IS_WIN32_PATH = new RegExp("^[a-zA-Z]:\\\\", "i");
141
- var IS_ALMOST_POSIX_PATH = new RegExp("^[a-zA-Z]:/", "i");
142
-
143
- // src/serverapi.ts
144
- function createServerAPI(endpoint, options) {
145
- endpoint += "/api/";
146
- const fetcher = options?.auth ? (url, init) => fetch(url, {
147
- ...init,
148
- headers: {
149
- ...init.headers,
150
- "Authorization": `Bearer ${options.auth}`
151
- }
152
- }) : fetch;
153
- if (options?.retries)
154
- return TypedHTTP.createClient(endpoint, (url, init) => retryWithBackoff(() => fetcher(url, init), options.retries));
155
- return TypedHTTP.createClient(endpoint, fetcher);
156
- }
157
-
158
- // src/reportUploader.ts
159
- var ReportUploader = class _ReportUploader {
160
- static optionsFromEnv(overrides) {
161
- const flakinessAccessToken = overrides?.flakinessAccessToken ?? process.env["FLAKINESS_ACCESS_TOKEN"];
162
- if (!flakinessAccessToken)
163
- return void 0;
164
- const flakinessEndpoint = overrides?.flakinessEndpoint ?? process.env["FLAKINESS_ENDPOINT"] ?? "https://flakiness.io";
165
- return { flakinessAccessToken, flakinessEndpoint };
166
- }
167
- static async upload(options) {
168
- const uploaderOptions = _ReportUploader.optionsFromEnv(options);
169
- if (!uploaderOptions) {
170
- if (process.env.CI)
171
- options.log?.(`[flakiness.io] Uploading skipped since no FLAKINESS_ACCESS_TOKEN is specified`);
172
- return void 0;
173
- }
174
- const uploader = new _ReportUploader(uploaderOptions);
175
- const upload = uploader.createUpload(options.report, options.attachments);
176
- const uploadResult = await upload.upload();
177
- if (!uploadResult.success) {
178
- options.log?.(`[flakiness.io] X Failed to upload to ${uploaderOptions.flakinessEndpoint}: ${uploadResult.message}`);
179
- return { errorMessage: uploadResult.message };
180
- }
181
- options.log?.(`[flakiness.io] \u2713 Report uploaded ${uploadResult.message ?? ""}`);
182
- if (uploadResult.reportUrl)
183
- options.log?.(`[flakiness.io] ${uploadResult.reportUrl}`);
184
- }
185
- _options;
186
- constructor(options) {
187
- this._options = options;
188
- }
189
- createUpload(report, attachments) {
190
- const upload = new ReportUpload(this._options, report, attachments);
191
- return upload;
192
- }
193
- };
194
- var HTTP_BACKOFF = [100, 500, 1e3, 1e3, 1e3, 1e3];
195
- var ReportUpload = class {
196
- _report;
197
- _attachments;
198
- _options;
199
- _api;
200
- constructor(options, report, attachments) {
201
- this._options = options;
202
- this._report = report;
203
- this._attachments = attachments;
204
- this._api = createServerAPI(this._options.flakinessEndpoint, { retries: HTTP_BACKOFF, auth: this._options.flakinessAccessToken });
205
- }
206
- async upload(options) {
207
- const response = await this._api.run.startUpload.POST({
208
- attachmentIds: this._attachments.map((attachment) => attachment.id)
209
- }).then((result) => ({ result, error: void 0 })).catch((e) => ({ result: void 0, error: e }));
210
- if (response?.error || !response.result)
211
- return { success: false, message: `flakiness.io returned error: ${response.error.message}` };
212
- await Promise.all([
213
- this._uploadReport(JSON.stringify(this._report), response.result.report_upload_url, options?.syncCompression ?? false),
214
- ...this._attachments.map((attachment) => {
215
- const uploadURL = response.result.attachment_upload_urls[attachment.id];
216
- if (!uploadURL)
217
- throw new Error("Internal error: missing upload URL for attachment!");
218
- return this._uploadAttachment(attachment, uploadURL, options?.syncCompression ?? false);
219
- })
220
- ]);
221
- const response2 = await this._api.run.completeUpload.POST({
222
- upload_token: response.result.upload_token
223
- }).then((result) => ({ result, error: void 0 })).catch((e) => ({ error: e, result: void 0 }));
224
- const url = response2?.result?.report_url ? new URL(response2?.result.report_url, this._options.flakinessEndpoint).toString() : void 0;
225
- return { success: true, reportUrl: url };
226
- }
227
- async _uploadReport(data, uploadUrl, syncCompression) {
228
- const compressed = syncCompression ? compressTextSync(data) : await compressTextAsync(data);
229
- const headers = {
230
- "Content-Type": "application/json",
231
- "Content-Length": Buffer.byteLength(compressed) + "",
232
- "Content-Encoding": "br"
233
- };
234
- await retryWithBackoff(async () => {
235
- const { request, responseDataPromise } = httpUtils.createRequest({
236
- url: uploadUrl,
237
- headers,
238
- method: "put"
239
- });
240
- request.write(compressed);
241
- request.end();
242
- await responseDataPromise;
243
- }, HTTP_BACKOFF);
244
- }
245
- async _uploadAttachment(attachment, uploadUrl, syncCompression) {
246
- const mimeType = attachment.contentType.toLocaleLowerCase().trim();
247
- const compressable = mimeType.startsWith("text/") || mimeType.endsWith("+json") || mimeType.endsWith("+text") || mimeType.endsWith("+xml");
248
- if (!compressable && attachment.path) {
249
- const attachmentPath = attachment.path;
250
- await retryWithBackoff(async () => {
251
- const { request, responseDataPromise } = httpUtils.createRequest({
252
- url: uploadUrl,
253
- headers: {
254
- "Content-Type": attachment.contentType,
255
- "Content-Length": (await fs2.promises.stat(attachmentPath)).size + ""
256
- },
257
- method: "put"
258
- });
259
- fs2.createReadStream(attachmentPath).pipe(request);
260
- await responseDataPromise;
261
- }, HTTP_BACKOFF);
262
- return;
263
- }
264
- let buffer = attachment.body ? attachment.body : attachment.path ? await fs2.promises.readFile(attachment.path) : void 0;
265
- assert(buffer);
266
- const encoding = compressable ? "br" : void 0;
267
- if (compressable)
268
- buffer = syncCompression ? compressTextSync(buffer) : await compressTextAsync(buffer);
269
- const headers = {
270
- "Content-Type": attachment.contentType,
271
- "Content-Length": Buffer.byteLength(buffer) + "",
272
- "Content-Encoding": encoding
273
- };
274
- await retryWithBackoff(async () => {
275
- const { request, responseDataPromise } = httpUtils.createRequest({
276
- url: uploadUrl,
277
- headers,
278
- method: "put"
279
- });
280
- request.write(buffer);
281
- request.end();
282
- await responseDataPromise;
283
- }, HTTP_BACKOFF);
284
- }
285
- };
286
-
287
- // src/cli/cmd-upload.ts
288
- var warn = (txt) => console.warn(chalk.yellow(`[flakiness.io] WARN: ${txt}`));
289
- var err = (txt) => console.error(chalk.red(`[flakiness.io] Error: ${txt}`));
290
- var log = (txt) => console.log(`[flakiness.io] ${txt}`);
291
- async function cmdUpload(relativePaths, options) {
292
- const uploader = new ReportUploader({
293
- flakinessAccessToken: options.accessToken,
294
- flakinessEndpoint: options.endpoint
295
- });
296
- for (const relativePath of relativePaths) {
297
- const fullPath = path2.resolve(relativePath);
298
- if (!await fs3.access(fullPath, fs3.constants.F_OK).then(() => true).catch(() => false)) {
299
- err(`Path ${fullPath} is not accessible!`);
300
- process.exit(1);
301
- }
302
- const text = await fs3.readFile(fullPath, "utf-8");
303
- const report = JSON.parse(text);
304
- const attachmentsDir = options.attachmentsDir ?? path2.dirname(fullPath);
305
- const { attachmentIdToPath, missingAttachments } = await resolveAttachmentPaths(report, attachmentsDir);
306
- if (missingAttachments.length) {
307
- warn(`Missing ${missingAttachments.length} attachments`);
308
- }
309
- const upload = uploader.createUpload(report, Array.from(attachmentIdToPath.values()));
310
- const uploadResult = await upload.upload();
311
- if (!uploadResult.success) {
312
- err(`Failed to upload to ${options.endpoint}: ${uploadResult.message}`);
313
- } else {
314
- log(`\u2713 Uploaded ${uploadResult.reportUrl ?? uploadResult.message ?? ""}`);
315
- }
316
- }
317
- }
318
- export {
319
- cmdUpload
320
- };
321
- //# sourceMappingURL=cmd-upload.js.map
@@ -1,173 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/flakinessSession.ts
4
- import fs from "fs/promises";
5
- import os from "os";
6
- import path from "path";
7
-
8
- // src/serverapi.ts
9
- import { TypedHTTP } from "@flakiness/shared/common/typedHttp.js";
10
-
11
- // src/utils.ts
12
- import { ReportUtils } from "@flakiness/report";
13
- import http from "http";
14
- import https from "https";
15
- var FLAKINESS_DBG = !!process.env.FLAKINESS_DBG;
16
- function errorText(error) {
17
- return FLAKINESS_DBG ? error.stack : error.message;
18
- }
19
- async function retryWithBackoff(job, backoff = []) {
20
- for (const timeout of backoff) {
21
- try {
22
- return await job();
23
- } catch (e) {
24
- if (e instanceof AggregateError)
25
- console.error(`[flakiness.io err]`, errorText(e.errors[0]));
26
- else if (e instanceof Error)
27
- console.error(`[flakiness.io err]`, errorText(e));
28
- else
29
- console.error(`[flakiness.io err]`, e);
30
- await new Promise((x) => setTimeout(x, timeout));
31
- }
32
- }
33
- return await job();
34
- }
35
- var httpUtils;
36
- ((httpUtils2) => {
37
- function createRequest({ url, method = "get", headers = {} }) {
38
- let resolve;
39
- let reject;
40
- const responseDataPromise = new Promise((a, b) => {
41
- resolve = a;
42
- reject = b;
43
- });
44
- const protocol = url.startsWith("https") ? https : http;
45
- headers = Object.fromEntries(Object.entries(headers).filter(([key, value]) => value !== void 0));
46
- const request = protocol.request(url, { method, headers }, (res) => {
47
- const chunks = [];
48
- res.on("data", (chunk) => chunks.push(chunk));
49
- res.on("end", () => {
50
- if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
51
- resolve(Buffer.concat(chunks));
52
- else
53
- reject(new Error(`Request to ${url} failed with ${res.statusCode}`));
54
- });
55
- res.on("error", (error) => reject(error));
56
- });
57
- request.on("error", reject);
58
- return { request, responseDataPromise };
59
- }
60
- httpUtils2.createRequest = createRequest;
61
- async function getBuffer(url, backoff) {
62
- return await retryWithBackoff(async () => {
63
- const { request, responseDataPromise } = createRequest({ url });
64
- request.end();
65
- return await responseDataPromise;
66
- }, backoff);
67
- }
68
- httpUtils2.getBuffer = getBuffer;
69
- async function getText(url, backoff) {
70
- const buffer = await getBuffer(url, backoff);
71
- return buffer.toString("utf-8");
72
- }
73
- httpUtils2.getText = getText;
74
- async function getJSON(url) {
75
- return JSON.parse(await getText(url));
76
- }
77
- httpUtils2.getJSON = getJSON;
78
- async function postText(url, text, backoff) {
79
- const headers = {
80
- "Content-Type": "application/json",
81
- "Content-Length": Buffer.byteLength(text) + ""
82
- };
83
- return await retryWithBackoff(async () => {
84
- const { request, responseDataPromise } = createRequest({ url, headers, method: "post" });
85
- request.write(text);
86
- request.end();
87
- return await responseDataPromise;
88
- }, backoff);
89
- }
90
- httpUtils2.postText = postText;
91
- async function postJSON(url, json, backoff) {
92
- const buffer = await postText(url, JSON.stringify(json), backoff);
93
- return JSON.parse(buffer.toString("utf-8"));
94
- }
95
- httpUtils2.postJSON = postJSON;
96
- })(httpUtils || (httpUtils = {}));
97
- 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");
98
- var IS_WIN32_PATH = new RegExp("^[a-zA-Z]:\\\\", "i");
99
- var IS_ALMOST_POSIX_PATH = new RegExp("^[a-zA-Z]:/", "i");
100
-
101
- // src/serverapi.ts
102
- function createServerAPI(endpoint, options) {
103
- endpoint += "/api/";
104
- const fetcher = options?.auth ? (url, init) => fetch(url, {
105
- ...init,
106
- headers: {
107
- ...init.headers,
108
- "Authorization": `Bearer ${options.auth}`
109
- }
110
- }) : fetch;
111
- if (options?.retries)
112
- return TypedHTTP.createClient(endpoint, (url, init) => retryWithBackoff(() => fetcher(url, init), options.retries));
113
- return TypedHTTP.createClient(endpoint, fetcher);
114
- }
115
-
116
- // src/flakinessSession.ts
117
- var CONFIG_DIR = (() => {
118
- const configDir = process.platform === "darwin" ? path.join(os.homedir(), "Library", "Application Support", "flakiness") : process.platform === "win32" ? path.join(os.homedir(), "AppData", "Roaming", "flakiness") : path.join(os.homedir(), ".config", "flakiness");
119
- return configDir;
120
- })();
121
- var CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
122
- var FlakinessSession = class _FlakinessSession {
123
- constructor(_config) {
124
- this._config = _config;
125
- this.api = createServerAPI(this._config.endpoint, { auth: this._config.token });
126
- }
127
- static async loadOrDie() {
128
- const session = await _FlakinessSession.load();
129
- if (!session)
130
- throw new Error(`Please login first with 'npx flakiness login'`);
131
- return session;
132
- }
133
- static async load() {
134
- const data = await fs.readFile(CONFIG_PATH, "utf-8").catch((e) => void 0);
135
- if (!data)
136
- return void 0;
137
- const json = JSON.parse(data);
138
- return new _FlakinessSession(json);
139
- }
140
- static async remove() {
141
- await fs.unlink(CONFIG_PATH).catch((e) => void 0);
142
- }
143
- api;
144
- endpoint() {
145
- return this._config.endpoint;
146
- }
147
- path() {
148
- return CONFIG_PATH;
149
- }
150
- sessionToken() {
151
- return this._config.token;
152
- }
153
- async save() {
154
- await fs.mkdir(CONFIG_DIR, { recursive: true });
155
- await fs.writeFile(CONFIG_PATH, JSON.stringify(this._config, null, 2));
156
- }
157
- };
158
-
159
- // src/cli/cmd-whoami.ts
160
- async function cmdWhoami() {
161
- const session = await FlakinessSession.load();
162
- if (!session) {
163
- console.log('Not logged in. Run "flakiness login" first.');
164
- process.exit(1);
165
- }
166
- console.log(`Logged into ${session.endpoint()}`);
167
- const user = await session.api.user.whoami.GET();
168
- console.log(user);
169
- }
170
- export {
171
- cmdWhoami
172
- };
173
- //# sourceMappingURL=cmd-whoami.js.map
@@ -1,159 +0,0 @@
1
- // src/flakinessSession.ts
2
- import fs from "fs/promises";
3
- import os from "os";
4
- import path from "path";
5
-
6
- // src/serverapi.ts
7
- import { TypedHTTP } from "@flakiness/shared/common/typedHttp.js";
8
-
9
- // src/utils.ts
10
- import { ReportUtils } from "@flakiness/report";
11
- import http from "http";
12
- import https from "https";
13
- var FLAKINESS_DBG = !!process.env.FLAKINESS_DBG;
14
- function errorText(error) {
15
- return FLAKINESS_DBG ? error.stack : error.message;
16
- }
17
- async function retryWithBackoff(job, backoff = []) {
18
- for (const timeout of backoff) {
19
- try {
20
- return await job();
21
- } catch (e) {
22
- if (e instanceof AggregateError)
23
- console.error(`[flakiness.io err]`, errorText(e.errors[0]));
24
- else if (e instanceof Error)
25
- console.error(`[flakiness.io err]`, errorText(e));
26
- else
27
- console.error(`[flakiness.io err]`, e);
28
- await new Promise((x) => setTimeout(x, timeout));
29
- }
30
- }
31
- return await job();
32
- }
33
- var httpUtils;
34
- ((httpUtils2) => {
35
- function createRequest({ url, method = "get", headers = {} }) {
36
- let resolve;
37
- let reject;
38
- const responseDataPromise = new Promise((a, b) => {
39
- resolve = a;
40
- reject = b;
41
- });
42
- const protocol = url.startsWith("https") ? https : http;
43
- headers = Object.fromEntries(Object.entries(headers).filter(([key, value]) => value !== void 0));
44
- const request = protocol.request(url, { method, headers }, (res) => {
45
- const chunks = [];
46
- res.on("data", (chunk) => chunks.push(chunk));
47
- res.on("end", () => {
48
- if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
49
- resolve(Buffer.concat(chunks));
50
- else
51
- reject(new Error(`Request to ${url} failed with ${res.statusCode}`));
52
- });
53
- res.on("error", (error) => reject(error));
54
- });
55
- request.on("error", reject);
56
- return { request, responseDataPromise };
57
- }
58
- httpUtils2.createRequest = createRequest;
59
- async function getBuffer(url, backoff) {
60
- return await retryWithBackoff(async () => {
61
- const { request, responseDataPromise } = createRequest({ url });
62
- request.end();
63
- return await responseDataPromise;
64
- }, backoff);
65
- }
66
- httpUtils2.getBuffer = getBuffer;
67
- async function getText(url, backoff) {
68
- const buffer = await getBuffer(url, backoff);
69
- return buffer.toString("utf-8");
70
- }
71
- httpUtils2.getText = getText;
72
- async function getJSON(url) {
73
- return JSON.parse(await getText(url));
74
- }
75
- httpUtils2.getJSON = getJSON;
76
- async function postText(url, text, backoff) {
77
- const headers = {
78
- "Content-Type": "application/json",
79
- "Content-Length": Buffer.byteLength(text) + ""
80
- };
81
- return await retryWithBackoff(async () => {
82
- const { request, responseDataPromise } = createRequest({ url, headers, method: "post" });
83
- request.write(text);
84
- request.end();
85
- return await responseDataPromise;
86
- }, backoff);
87
- }
88
- httpUtils2.postText = postText;
89
- async function postJSON(url, json, backoff) {
90
- const buffer = await postText(url, JSON.stringify(json), backoff);
91
- return JSON.parse(buffer.toString("utf-8"));
92
- }
93
- httpUtils2.postJSON = postJSON;
94
- })(httpUtils || (httpUtils = {}));
95
- 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");
96
- var IS_WIN32_PATH = new RegExp("^[a-zA-Z]:\\\\", "i");
97
- var IS_ALMOST_POSIX_PATH = new RegExp("^[a-zA-Z]:/", "i");
98
-
99
- // src/serverapi.ts
100
- function createServerAPI(endpoint, options) {
101
- endpoint += "/api/";
102
- const fetcher = options?.auth ? (url, init) => fetch(url, {
103
- ...init,
104
- headers: {
105
- ...init.headers,
106
- "Authorization": `Bearer ${options.auth}`
107
- }
108
- }) : fetch;
109
- if (options?.retries)
110
- return TypedHTTP.createClient(endpoint, (url, init) => retryWithBackoff(() => fetcher(url, init), options.retries));
111
- return TypedHTTP.createClient(endpoint, fetcher);
112
- }
113
-
114
- // src/flakinessSession.ts
115
- var CONFIG_DIR = (() => {
116
- const configDir = process.platform === "darwin" ? path.join(os.homedir(), "Library", "Application Support", "flakiness") : process.platform === "win32" ? path.join(os.homedir(), "AppData", "Roaming", "flakiness") : path.join(os.homedir(), ".config", "flakiness");
117
- return configDir;
118
- })();
119
- var CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
120
- var FlakinessSession = class _FlakinessSession {
121
- constructor(_config) {
122
- this._config = _config;
123
- this.api = createServerAPI(this._config.endpoint, { auth: this._config.token });
124
- }
125
- static async loadOrDie() {
126
- const session = await _FlakinessSession.load();
127
- if (!session)
128
- throw new Error(`Please login first with 'npx flakiness login'`);
129
- return session;
130
- }
131
- static async load() {
132
- const data = await fs.readFile(CONFIG_PATH, "utf-8").catch((e) => void 0);
133
- if (!data)
134
- return void 0;
135
- const json = JSON.parse(data);
136
- return new _FlakinessSession(json);
137
- }
138
- static async remove() {
139
- await fs.unlink(CONFIG_PATH).catch((e) => void 0);
140
- }
141
- api;
142
- endpoint() {
143
- return this._config.endpoint;
144
- }
145
- path() {
146
- return CONFIG_PATH;
147
- }
148
- sessionToken() {
149
- return this._config.token;
150
- }
151
- async save() {
152
- await fs.mkdir(CONFIG_DIR, { recursive: true });
153
- await fs.writeFile(CONFIG_PATH, JSON.stringify(this._config, null, 2));
154
- }
155
- };
156
- export {
157
- FlakinessSession
158
- };
159
- //# sourceMappingURL=flakinessSession.js.map