@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,414 @@
1
+ // ../server/lib/common/knownClientIds.js
2
+ var KNOWN_CLIENT_IDS = {
3
+ OFFICIAL_WEB: "flakiness-io-official-cli",
4
+ OFFICIAL_CLI: "flakiness-io-official-website"
5
+ };
6
+
7
+ // src/cli/cmd-login.ts
8
+ import os2 from "os";
9
+
10
+ // src/flakinessSession.ts
11
+ import fs from "fs/promises";
12
+ import os from "os";
13
+ import path from "path";
14
+
15
+ // ../server/lib/common/typedHttp.js
16
+ var TypedHTTP;
17
+ ((TypedHTTP2) => {
18
+ TypedHTTP2.StatusCodes = {
19
+ Informational: {
20
+ CONTINUE: 100,
21
+ SWITCHING_PROTOCOLS: 101,
22
+ PROCESSING: 102,
23
+ EARLY_HINTS: 103
24
+ },
25
+ Success: {
26
+ OK: 200,
27
+ CREATED: 201,
28
+ ACCEPTED: 202,
29
+ NON_AUTHORITATIVE_INFORMATION: 203,
30
+ NO_CONTENT: 204,
31
+ RESET_CONTENT: 205,
32
+ PARTIAL_CONTENT: 206,
33
+ MULTI_STATUS: 207
34
+ },
35
+ Redirection: {
36
+ MULTIPLE_CHOICES: 300,
37
+ MOVED_PERMANENTLY: 301,
38
+ MOVED_TEMPORARILY: 302,
39
+ SEE_OTHER: 303,
40
+ NOT_MODIFIED: 304,
41
+ USE_PROXY: 305,
42
+ TEMPORARY_REDIRECT: 307,
43
+ PERMANENT_REDIRECT: 308
44
+ },
45
+ ClientErrors: {
46
+ BAD_REQUEST: 400,
47
+ UNAUTHORIZED: 401,
48
+ PAYMENT_REQUIRED: 402,
49
+ FORBIDDEN: 403,
50
+ NOT_FOUND: 404,
51
+ METHOD_NOT_ALLOWED: 405,
52
+ NOT_ACCEPTABLE: 406,
53
+ PROXY_AUTHENTICATION_REQUIRED: 407,
54
+ REQUEST_TIMEOUT: 408,
55
+ CONFLICT: 409,
56
+ GONE: 410,
57
+ LENGTH_REQUIRED: 411,
58
+ PRECONDITION_FAILED: 412,
59
+ REQUEST_TOO_LONG: 413,
60
+ REQUEST_URI_TOO_LONG: 414,
61
+ UNSUPPORTED_MEDIA_TYPE: 415,
62
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416,
63
+ EXPECTATION_FAILED: 417,
64
+ IM_A_TEAPOT: 418,
65
+ INSUFFICIENT_SPACE_ON_RESOURCE: 419,
66
+ METHOD_FAILURE: 420,
67
+ MISDIRECTED_REQUEST: 421,
68
+ UNPROCESSABLE_ENTITY: 422,
69
+ LOCKED: 423,
70
+ FAILED_DEPENDENCY: 424,
71
+ UPGRADE_REQUIRED: 426,
72
+ PRECONDITION_REQUIRED: 428,
73
+ TOO_MANY_REQUESTS: 429,
74
+ REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
75
+ UNAVAILABLE_FOR_LEGAL_REASONS: 451
76
+ },
77
+ ServerErrors: {
78
+ INTERNAL_SERVER_ERROR: 500,
79
+ NOT_IMPLEMENTED: 501,
80
+ BAD_GATEWAY: 502,
81
+ SERVICE_UNAVAILABLE: 503,
82
+ GATEWAY_TIMEOUT: 504,
83
+ HTTP_VERSION_NOT_SUPPORTED: 505,
84
+ INSUFFICIENT_STORAGE: 507,
85
+ NETWORK_AUTHENTICATION_REQUIRED: 511
86
+ }
87
+ };
88
+ const AllErrorCodes = {
89
+ ...TypedHTTP2.StatusCodes.ClientErrors,
90
+ ...TypedHTTP2.StatusCodes.ServerErrors
91
+ };
92
+ class HttpError extends Error {
93
+ constructor(status, message) {
94
+ super(message);
95
+ this.status = status;
96
+ }
97
+ static withCode(code, message) {
98
+ const statusCode = AllErrorCodes[code];
99
+ const defaultMessage = code.split("_").map((word) => word.charAt(0) + word.slice(1).toLowerCase()).join(" ");
100
+ return new HttpError(statusCode, message ?? defaultMessage);
101
+ }
102
+ }
103
+ TypedHTTP2.HttpError = HttpError;
104
+ function isInformationalResponse(response) {
105
+ return response.status >= 100 && response.status < 200;
106
+ }
107
+ TypedHTTP2.isInformationalResponse = isInformationalResponse;
108
+ function isSuccessResponse(response) {
109
+ return response.status >= 200 && response.status < 300;
110
+ }
111
+ TypedHTTP2.isSuccessResponse = isSuccessResponse;
112
+ function isRedirectResponse(response) {
113
+ return response.status >= 300 && response.status < 400;
114
+ }
115
+ TypedHTTP2.isRedirectResponse = isRedirectResponse;
116
+ function isErrorResponse(response) {
117
+ return response.status >= 400 && response.status < 600;
118
+ }
119
+ TypedHTTP2.isErrorResponse = isErrorResponse;
120
+ function info(status) {
121
+ return { status };
122
+ }
123
+ TypedHTTP2.info = info;
124
+ function ok(data, status) {
125
+ return {
126
+ status: status ?? TypedHTTP2.StatusCodes.Success.OK,
127
+ data
128
+ };
129
+ }
130
+ TypedHTTP2.ok = ok;
131
+ function redirect(url, status = 302) {
132
+ return { status, url };
133
+ }
134
+ TypedHTTP2.redirect = redirect;
135
+ function error(message, status = TypedHTTP2.StatusCodes.ServerErrors.INTERNAL_SERVER_ERROR) {
136
+ return { status, message };
137
+ }
138
+ TypedHTTP2.error = error;
139
+ class Router {
140
+ constructor(_resolveContext) {
141
+ this._resolveContext = _resolveContext;
142
+ }
143
+ static create() {
144
+ return new Router(async (e) => e.ctx);
145
+ }
146
+ rawMethod(method, route) {
147
+ return {
148
+ [method]: {
149
+ method,
150
+ input: route.input,
151
+ etag: route.etag,
152
+ resolveContext: this._resolveContext,
153
+ handler: route.handler
154
+ }
155
+ };
156
+ }
157
+ get(route) {
158
+ return this.rawMethod("GET", {
159
+ ...route,
160
+ handler: (...args) => Promise.resolve(route.handler(...args)).then((result) => TypedHTTP2.ok(result))
161
+ });
162
+ }
163
+ post(route) {
164
+ return this.rawMethod("POST", {
165
+ ...route,
166
+ handler: (...args) => Promise.resolve(route.handler(...args)).then((result) => TypedHTTP2.ok(result))
167
+ });
168
+ }
169
+ use(resolveContext) {
170
+ return new Router(async (options) => {
171
+ const m = await this._resolveContext(options);
172
+ return resolveContext({ ...options, ctx: m });
173
+ });
174
+ }
175
+ }
176
+ TypedHTTP2.Router = Router;
177
+ function createClient(base, fetchCallback) {
178
+ function buildUrl(path2, input, options) {
179
+ const method = path2.at(-1);
180
+ const url = new URL(path2.slice(0, path2.length - 1).join("/"), base);
181
+ const signal = options?.signal;
182
+ let body = void 0;
183
+ if (method === "GET" && input)
184
+ url.searchParams.set("input", JSON.stringify(input));
185
+ else if (method !== "GET" && input)
186
+ body = JSON.stringify(input);
187
+ return {
188
+ url,
189
+ method,
190
+ headers: body ? { "Content-Type": "application/json" } : void 0,
191
+ body,
192
+ signal
193
+ };
194
+ }
195
+ function createProxy(path2 = []) {
196
+ return new Proxy(() => {
197
+ }, {
198
+ get(target, prop) {
199
+ if (typeof prop === "symbol")
200
+ return void 0;
201
+ if (prop === "prepare")
202
+ return (input, options) => buildUrl(path2, input, options);
203
+ const newPath = [...path2, prop];
204
+ return createProxy(newPath);
205
+ },
206
+ apply(target, thisArg, args) {
207
+ const options = buildUrl(path2, args[0], args[1]);
208
+ return fetchCallback(options.url, {
209
+ method: options.method,
210
+ body: options.body,
211
+ headers: options.headers,
212
+ signal: options.signal
213
+ }).then(async (response) => {
214
+ if (response.status >= 200 && response.status < 300) {
215
+ if (response.headers.get("content-type")?.includes("application/json")) {
216
+ const text = await response.text();
217
+ return text.length ? JSON.parse(text) : void 0;
218
+ }
219
+ return await response.blob();
220
+ }
221
+ if (response.status >= 400 && response.status < 600) {
222
+ const text = await response.text();
223
+ if (text)
224
+ throw new Error(`HTTP request failed with status ${response.status}: ${text}`);
225
+ else
226
+ throw new Error(`HTTP request failed with status ${response.status}`);
227
+ }
228
+ });
229
+ }
230
+ });
231
+ }
232
+ return createProxy();
233
+ }
234
+ TypedHTTP2.createClient = createClient;
235
+ })(TypedHTTP || (TypedHTTP = {}));
236
+
237
+ // src/utils.ts
238
+ import http from "http";
239
+ import https from "https";
240
+ import util from "util";
241
+ import zlib from "zlib";
242
+ var gzipAsync = util.promisify(zlib.gzip);
243
+ var gunzipAsync = util.promisify(zlib.gunzip);
244
+ var gunzipSync = zlib.gunzipSync;
245
+ var brotliCompressAsync = util.promisify(zlib.brotliCompress);
246
+ var brotliCompressSync = zlib.brotliCompressSync;
247
+ async function retryWithBackoff(job, backoff = []) {
248
+ for (const timeout of backoff) {
249
+ try {
250
+ return await job();
251
+ } catch (e) {
252
+ if (e instanceof AggregateError)
253
+ console.error(`[flakiness.io err]`, e.errors[0].message);
254
+ else if (e instanceof Error)
255
+ console.error(`[flakiness.io err]`, e.message);
256
+ else
257
+ console.error(`[flakiness.io err]`, e);
258
+ await new Promise((x) => setTimeout(x, timeout));
259
+ }
260
+ }
261
+ return await job();
262
+ }
263
+ var httpUtils;
264
+ ((httpUtils2) => {
265
+ function createRequest({ url, method = "get", headers = {} }) {
266
+ let resolve;
267
+ let reject;
268
+ const responseDataPromise = new Promise((a, b) => {
269
+ resolve = a;
270
+ reject = b;
271
+ });
272
+ const protocol = url.startsWith("https") ? https : http;
273
+ const request = protocol.request(url, { method, headers }, (res) => {
274
+ const chunks = [];
275
+ res.on("data", (chunk) => chunks.push(chunk));
276
+ res.on("end", () => {
277
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
278
+ resolve(Buffer.concat(chunks));
279
+ else
280
+ reject(new Error(`Request to ${url} failed with ${res.statusCode}`));
281
+ });
282
+ res.on("error", (error) => reject(error));
283
+ });
284
+ request.on("error", reject);
285
+ return { request, responseDataPromise };
286
+ }
287
+ httpUtils2.createRequest = createRequest;
288
+ async function getBuffer(url, backoff) {
289
+ return await retryWithBackoff(async () => {
290
+ const { request, responseDataPromise } = createRequest({ url });
291
+ request.end();
292
+ return await responseDataPromise;
293
+ }, backoff);
294
+ }
295
+ httpUtils2.getBuffer = getBuffer;
296
+ async function getText(url, backoff) {
297
+ const buffer = await getBuffer(url, backoff);
298
+ return buffer.toString("utf-8");
299
+ }
300
+ httpUtils2.getText = getText;
301
+ async function getJSON(url) {
302
+ return JSON.parse(await getText(url));
303
+ }
304
+ httpUtils2.getJSON = getJSON;
305
+ async function postText(url, text, backoff) {
306
+ const headers = {
307
+ "Content-Type": "application/json",
308
+ "Content-Length": Buffer.byteLength(text) + ""
309
+ };
310
+ return await retryWithBackoff(async () => {
311
+ const { request, responseDataPromise } = createRequest({ url, headers, method: "post" });
312
+ request.write(text);
313
+ request.end();
314
+ return await responseDataPromise;
315
+ }, backoff);
316
+ }
317
+ httpUtils2.postText = postText;
318
+ async function postJSON(url, json, backoff) {
319
+ const buffer = await postText(url, JSON.stringify(json), backoff);
320
+ return JSON.parse(buffer.toString("utf-8"));
321
+ }
322
+ httpUtils2.postJSON = postJSON;
323
+ })(httpUtils || (httpUtils = {}));
324
+ 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");
325
+ var IS_WIN32_PATH = new RegExp("^[a-zA-Z]:\\\\", "i");
326
+ var IS_ALMOST_POSIX_PATH = new RegExp("^[a-zA-Z]:/", "i");
327
+
328
+ // src/serverapi.ts
329
+ function createServerAPI(endpoint, options) {
330
+ endpoint += "/api/";
331
+ const fetcher = options?.auth ? (url, init) => fetch(url, {
332
+ ...init,
333
+ headers: {
334
+ ...init.headers,
335
+ "Authorization": `Bearer ${options.auth}`
336
+ }
337
+ }) : fetch;
338
+ if (options?.retries)
339
+ return TypedHTTP.createClient(endpoint, (url, init) => retryWithBackoff(() => fetcher(url, init), options.retries));
340
+ return TypedHTTP.createClient(endpoint, fetcher);
341
+ }
342
+
343
+ // src/flakinessSession.ts
344
+ var CONFIG_DIR = (() => {
345
+ 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");
346
+ return configDir;
347
+ })();
348
+ var CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
349
+ var FlakinessSession = class _FlakinessSession {
350
+ constructor(_config) {
351
+ this._config = _config;
352
+ this.api = createServerAPI(this._config.endpoint, { auth: this._config.token });
353
+ }
354
+ static async load() {
355
+ const data = await fs.readFile(CONFIG_PATH, "utf-8").catch((e) => void 0);
356
+ if (!data)
357
+ return void 0;
358
+ const json = JSON.parse(data);
359
+ return new _FlakinessSession(json);
360
+ }
361
+ static async remove() {
362
+ await fs.unlink(CONFIG_PATH).catch((e) => void 0);
363
+ }
364
+ api;
365
+ endpoint() {
366
+ return this._config.endpoint;
367
+ }
368
+ path() {
369
+ return CONFIG_PATH;
370
+ }
371
+ sessionToken() {
372
+ return this._config.token;
373
+ }
374
+ async save() {
375
+ await fs.mkdir(CONFIG_DIR, { recursive: true });
376
+ await fs.writeFile(CONFIG_PATH, JSON.stringify(this._config, null, 2));
377
+ }
378
+ };
379
+
380
+ // src/cli/cmd-login.ts
381
+ async function cmdLogin(endpoint) {
382
+ const api = createServerAPI(endpoint);
383
+ const data = await api.deviceauth.createRequest.POST({
384
+ clientId: KNOWN_CLIENT_IDS.OFFICIAL_CLI,
385
+ name: os2.hostname()
386
+ });
387
+ console.log(`Please navigate to ${new URL(data.verificationUrl, endpoint)}`);
388
+ let token;
389
+ while (Date.now() < data.deadline) {
390
+ await new Promise((x) => setTimeout(x, 2e3));
391
+ const result = await api.deviceauth.getToken.GET({ deviceCode: data.deviceCode }).catch((e) => void 0);
392
+ if (!result) {
393
+ console.log(`Authorization request was rejected.`);
394
+ return;
395
+ }
396
+ token = result.token;
397
+ if (token)
398
+ break;
399
+ }
400
+ if (!token) {
401
+ console.log(`Failed to login.`);
402
+ process.exit(1);
403
+ }
404
+ const session = new FlakinessSession({
405
+ endpoint,
406
+ token
407
+ });
408
+ await session.save();
409
+ console.log(`\u2713 Login successful! Token saved to ${session.path()}`);
410
+ }
411
+ export {
412
+ cmdLogin
413
+ };
414
+ //# sourceMappingURL=cmd-login.js.map