@trackunit/iris-app-e2e 1.8.85-alpha-20757f7c966.0 → 1.8.85

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.
package/index.cjs.js CHANGED
@@ -1,8 +1,28 @@
1
1
  'use strict';
2
2
 
3
- var installLogsCollector = require('cypress-terminal-report/src/installLogsCollector');
4
- require('@neuralegion/cypress-har-generator/commands');
5
- var fileNameBuilder = require('./fileNameBuilder.cjs.js');
3
+ var fs = require('fs');
4
+ var path = require('path');
5
+ var crypto = require('crypto');
6
+ var nodeXlsx = require('node-xlsx');
7
+
8
+ function _interopNamespaceDefault(e) {
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
6
26
 
7
27
  /**
8
28
  * Sets up default Cypress commands for E2E testing.
@@ -136,12 +156,367 @@ function setupDefaultCommands() {
136
156
  });
137
157
  }
138
158
 
159
+ /* eslint-disable no-console */
160
+ /**
161
+ * Writes a file with Prettier formatting applied.
162
+ * Automatically detects parser based on file extension.
163
+ */
164
+ const writeFileWithPrettier = async (nxRoot, filePath, content, writeOptions = { encoding: "utf-8" }, writer) => {
165
+ const prettierConfigPath = path__namespace.join(nxRoot, ".prettierrc");
166
+ const options = await writer
167
+ .resolveConfig(prettierConfigPath)
168
+ .catch(error => console.log("Prettier config error: ", error));
169
+ if (!options) {
170
+ throw new Error("Could not find prettier config");
171
+ }
172
+ if (filePath.endsWith("json")) {
173
+ options.parser = "json";
174
+ }
175
+ else {
176
+ options.parser = "typescript";
177
+ }
178
+ try {
179
+ const prettySrc = await writer.format(content, options);
180
+ fs.writeFileSync(filePath, prettySrc, writeOptions);
181
+ }
182
+ catch (error) {
183
+ console.error("Error in prettier.format:", error);
184
+ }
185
+ };
186
+
187
+ const isNetworkCall = (log) => {
188
+ return log.type === "cy:fetch" || log.type === "cy:request" || log.type === "cy:response" || log.type === "cy:xrh";
189
+ };
190
+ /**
191
+ * Creates log files for Cypress test runs.
192
+ * Generates separate files for all logs, errors, and network errors.
193
+ */
194
+ function createLogFile(nxRoot, logsPath, fileNameWithoutExtension, logs, logWriter) {
195
+ if (!fs.existsSync(logsPath)) {
196
+ fs.mkdirSync(logsPath, { recursive: true });
197
+ }
198
+ const logFilePath = path.join(logsPath, fileNameWithoutExtension);
199
+ writeFileWithPrettier(nxRoot, logFilePath + "-all.json", JSON.stringify(logs), { flag: "a" }, logWriter);
200
+ const errorCmds = logs.filter(log => log.severity === "error" &&
201
+ // This seems to be when apollo has cancelled requests it marks it as failed to fetch only on cypress ?!??
202
+ // might be fixed by https://github.com/Trackunit/manager/pull/12917
203
+ !log.message.includes("TypeError: Failed to fetch"));
204
+ if (errorCmds.length > 0) {
205
+ writeFileWithPrettier(nxRoot, logFilePath + "-errors.json", JSON.stringify(errorCmds), {
206
+ flag: "a",
207
+ }, logWriter);
208
+ }
209
+ const networkErrorsCmds = logs.filter(log => isNetworkCall(log) &&
210
+ !log.message.includes("Status: 200") &&
211
+ log.severity !== "success" &&
212
+ !log.message.includes("sentry.io/api/") &&
213
+ // This seems to be when apollo has cancelled requests it marks it as failed to fetch only on cypress ?!??
214
+ !log.message.includes("TypeError: Failed to fetch"));
215
+ if (networkErrorsCmds.length > 0) {
216
+ writeFileWithPrettier(nxRoot, logFilePath + "-network-errors.json", JSON.stringify(networkErrorsCmds), {
217
+ flag: "a",
218
+ }, logWriter);
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Parses lines from a CODEOWNERS‐style file into a mapping of patterns → owners.
224
+ * Skips blank lines and comments (lines beginning with `#`).
225
+ *
226
+ * @param {string[]} lines - Each element is a line from your CODEOWNERS file.
227
+ * @returns {Record<string, string>} An object whose keys are normalized path patterns (no leading/trailing slashes)
228
+ * and whose values are the owner (e.g. a GitHub team handle).
229
+ * @example
230
+ * ```ts
231
+ * const lines = [
232
+ * "# Our CODEOWNERS",
233
+ * "/src @team/backend",
234
+ * "README.md @team/docs",
235
+ * "", // blank lines ignored
236
+ * "# end of file"
237
+ * ];
238
+ * const owners = parseCodeowners(lines);
239
+ * // → { "src": "@team/backend", "README.md": "@team/docs" }
240
+ * ```
241
+ */
242
+ const parseCodeowners = (lines) => {
243
+ const patterns = {};
244
+ for (const line of lines) {
245
+ const trimmed = line.trim();
246
+ if (!trimmed || trimmed.startsWith("#")) {
247
+ continue;
248
+ }
249
+ const [pattern, owner] = trimmed.split(/\s+/, 2);
250
+ if (pattern && owner) {
251
+ const normalizedPattern = pattern.replace(/^\/+|\/+$/g, "");
252
+ patterns[normalizedPattern] = owner;
253
+ }
254
+ }
255
+ return patterns;
256
+ };
257
+ /**
258
+ * Converts a full team handle (potentially namespaced and with platform suffix)
259
+ * into its “short” team name.
260
+ *
261
+ * - Strips any leading `@org/` prefix
262
+ * - Removes `-be` or `-fe` suffix if present
263
+ *
264
+ * @param {string} teamName - e.g. `"@trackunit/backend-be"` or `"@trackunit/frontend-fe"`
265
+ * @returns {string} e.g. `"backend"` or `"frontend"`
266
+ * @example
267
+ * ```ts
268
+ * toShortTeamName("@trackunit/backend-be"); // → "backend"
269
+ * toShortTeamName("@trackunit/frontend-fe"); // → "frontend"
270
+ * toShortTeamName("infra"); // → "infra"
271
+ * ```
272
+ */
273
+ const toShortTeamName = (teamName) => {
274
+ if (!teamName) {
275
+ return undefined;
276
+ }
277
+ let shortName = teamName;
278
+ if (teamName.startsWith("@")) {
279
+ shortName = shortName.slice(shortName.indexOf("/") + 1);
280
+ }
281
+ if (shortName.endsWith("-be") || shortName.endsWith("-fe")) {
282
+ shortName = shortName.slice(0, shortName.lastIndexOf("-"));
283
+ }
284
+ return shortName;
285
+ };
286
+ /**
287
+ * Recursively looks up the CODEOWNER for a given file or directory path
288
+ * by reading your workspace’s CODEOWNERS file.
289
+ *
290
+ * Walks up the directory tree until it finds a matching pattern. If no
291
+ * deeper match is found but there is a `"."` entry, returns that.
292
+ *
293
+ * @param {string} currentPath - Absolute path to the file/directory you’re querying.
294
+ * @param {string} workspaceRoot - Absolute path to your repo/workspace root.
295
+ * @param {string} [codeownersFileName="TEAM_CODEOWNERS"] - Filename to read at the root.
296
+ * @returns {string|undefined} The owner handle (e.g. `"@team/backend"`) or `undefined` if none found.
297
+ * @example
298
+ * ```ts
299
+ * // Suppose your repo root has a TEAM_CODEOWNERS file containing:
300
+ * // src @team/backend
301
+ * // src/utils @team/utils
302
+ * // . @team/root
303
+ *
304
+ * const owner1 = getCodeowner(
305
+ * "/Users/alice/project/src/utils/helpers.ts",
306
+ * "/Users/alice/project"
307
+ * );
308
+ * // → "@team/utils"
309
+ *
310
+ * const owner2 = getCodeowner(
311
+ * "/Users/alice/project/other/file.txt",
312
+ * "/Users/alice/project"
313
+ * );
314
+ * // → "@team/root" (falls back to the "." entry)
315
+ * ```
316
+ */
317
+ const getCodeowner = (currentPath, workspaceRoot, codeownersFileName = "TEAM_CODEOWNERS") => {
318
+ if (!workspaceRoot) {
319
+ return undefined;
320
+ }
321
+ const codeownersPath = path.join(workspaceRoot, codeownersFileName);
322
+ if (!fs.existsSync(codeownersPath)) {
323
+ return undefined;
324
+ }
325
+ const codeownersLines = fs.readFileSync(codeownersPath, "utf8").split("\n");
326
+ const codeowners = parseCodeowners(codeownersLines);
327
+ let relPath = path
328
+ .relative(workspaceRoot, currentPath)
329
+ .replace(/\\/g, "/")
330
+ .replace(/^\/+|\/+$/g, "");
331
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
332
+ while (true) {
333
+ const codeowner = codeowners[relPath];
334
+ if (codeowner) {
335
+ return codeowner;
336
+ }
337
+ const parent = path.posix.dirname(relPath);
338
+ if ((parent === relPath || parent === ".") && codeowners["."]) {
339
+ return codeowners["."];
340
+ }
341
+ if (parent === relPath || parent === ".") {
342
+ break;
343
+ }
344
+ relPath = parent;
345
+ }
346
+ return undefined;
347
+ };
348
+
349
+ /**
350
+ * Sanitizes a string to be safe for use in filenames.
351
+ * Removes special characters and truncates if too long.
352
+ *
353
+ * @param str - The string to sanitize (e.g., test suite or test name)
354
+ * @returns {string} Sanitized string safe for filesystem use
355
+ */
356
+ function sanitizeForFilename(str) {
357
+ return str
358
+ .replace(/[^a-zA-Z0-9-_\s\[\]\(\)]/g, "") // Remove special chars - with exceptions
359
+ .replace(/-+/g, "-") // Collapse multiple hyphens into one
360
+ .replace(/\s+/g, " ") // Collapse multiple spaces into one
361
+ .replace(/^-|-$/g, ""); // Trim leading/trailing hyphens
362
+ }
363
+ /**
364
+ * Builds a standardized filename for test artifacts (e.g., HAR files, screenshots).
365
+ * Combines test name, state, and attempt number into a readable filename.
366
+ *
367
+ * @param testName - The name of the test (will be sanitized)
368
+ * @param state - The test state (e.g., 'passed', 'failed')
369
+ * @param currentRetry - The current retry attempt number (0-based)
370
+ * @returns {string} A sanitized filename in the format: "testName (state) (attempt N)"
371
+ * @example
372
+ * fileNameBuilder("Login Flow", "failed", 0)
373
+ * // Returns: "Login Flow (failed) (attempt 1)"
374
+ * @example
375
+ * fileNameBuilder("Test: with -> special chars", "passed", 2)
376
+ * // Returns: "Test with - special chars (passed) (attempt 3)"
377
+ */
378
+ function fileNameBuilder(testName, state, currentRetry) {
379
+ const fileName = `${testName} ${currentRetry !== undefined ? `(Attempt ${currentRetry + 1})` : ""} (${state.toLowerCase()})`;
380
+ return sanitizeForFilename(fileName);
381
+ }
382
+
383
+ /**
384
+ * Utility function to find NX workspace root by looking for nx.json or workspace.json.
385
+ * This is more reliable than hardcoded relative paths and works from any directory.
386
+ *
387
+ * @param startDir Starting directory for the search (defaults to current working directory)
388
+ * @returns {string} Absolute path to the workspace root
389
+ * @throws Error if workspace root cannot be found
390
+ */
391
+ function findWorkspaceRoot(startDir = process.cwd()) {
392
+ let currentDir = startDir;
393
+ while (currentDir !== path.dirname(currentDir)) {
394
+ if (fs.existsSync(path.join(currentDir, "nx.json")) || fs.existsSync(path.join(currentDir, "workspace.json"))) {
395
+ return currentDir;
396
+ }
397
+ currentDir = path.dirname(currentDir);
398
+ }
399
+ throw new Error("Could not find NX workspace root (nx.json or workspace.json not found)");
400
+ }
401
+ /**
402
+ * Creates default Cypress configuration for E2E testing.
403
+ * Supports both legacy string parameter (dirname) and new options object for backward compatibility.
404
+ */
405
+ const defaultCypressConfig = optionsOrDirname => {
406
+ // Support both old API (string/undefined) and new API (object) for backward compatibility
407
+ const options = typeof optionsOrDirname === "object" ? optionsOrDirname : {};
408
+ const { nxRoot: providedNxRoot, outputDirOverride, projectConfig = {}, behaviorConfig = {}, pluginConfig = {}, } = options;
409
+ // Use NX workspace detection for reliable root finding
410
+ const nxRoot = providedNxRoot ?? findWorkspaceRoot();
411
+ // For output path calculation, determine the relative path from caller to workspace root
412
+ const callerDirname = typeof optionsOrDirname === "string" ? optionsOrDirname : process.cwd();
413
+ const relativePath = path.relative(nxRoot, callerDirname);
414
+ const dotsToNxRoot = relativePath
415
+ .split(path.sep)
416
+ .map(_ => "..")
417
+ .join("/");
418
+ const envOutputDirOverride = process.env.NX_E2E_OUTPUT_DIR || outputDirOverride;
419
+ // Function to build output paths that respects the override
420
+ const buildOutputPath = (subPath) => {
421
+ if (envOutputDirOverride) {
422
+ return path.join(dotsToNxRoot, envOutputDirOverride, subPath);
423
+ }
424
+ return `${dotsToNxRoot}/dist/cypress/${relativePath}/${subPath}`;
425
+ };
426
+ return {
427
+ projectId: projectConfig.projectId ?? process.env.CYPRESS_PROJECT_ID,
428
+ defaultCommandTimeout: behaviorConfig.defaultCommandTimeout ?? 20000,
429
+ execTimeout: behaviorConfig.execTimeout ?? 300000,
430
+ taskTimeout: behaviorConfig.taskTimeout ?? 35000,
431
+ pageLoadTimeout: behaviorConfig.pageLoadTimeout ?? 35000,
432
+ // setting to undefined makes no effect on the baseUrl so child projects can override it
433
+ baseUrl: process.env.NX_FEATURE_BRANCH_BASE_URL ?? undefined,
434
+ // This avoid issues with SRI hashes changing
435
+ modifyObstructiveCode: false,
436
+ requestTimeout: behaviorConfig.requestTimeout ?? 25000,
437
+ responseTimeout: behaviorConfig.responseTimeout ?? 150000,
438
+ retries: behaviorConfig.retries ?? {
439
+ runMode: 3,
440
+ openMode: 0,
441
+ },
442
+ fixturesFolder: projectConfig.fixturesFolder ?? "./src/fixtures",
443
+ downloadsFolder: pluginConfig.outputPath ?? buildOutputPath("downloads"),
444
+ logsFolder: pluginConfig.logsFolder ?? buildOutputPath("logs"),
445
+ chromeWebSecurity: false,
446
+ reporter: "junit",
447
+ reporterOptions: {
448
+ mochaFile: buildOutputPath("results-[hash].xml"),
449
+ },
450
+ specPattern: projectConfig.specPattern ?? "src/e2e/**/*.e2e.{js,jsx,ts,tsx}",
451
+ supportFile: projectConfig.supportFile ?? "src/support/e2e.ts",
452
+ nxRoot,
453
+ fileServerFolder: ".",
454
+ video: true,
455
+ trashAssetsBeforeRuns: false, // Don't delete videos from previous test runs (important for sequential runs)
456
+ videosFolder: pluginConfig.videosFolder ?? buildOutputPath("videos"),
457
+ screenshotsFolder: pluginConfig.screenshotsFolder ?? buildOutputPath("screenshots"),
458
+ env: {
459
+ hars_folders: pluginConfig.harFolder ?? buildOutputPath("hars"),
460
+ CYPRESS_RUN_UNIQUE_ID: crypto.randomUUID(),
461
+ },
462
+ };
463
+ };
464
+ /**
465
+ * Sets up Cypress plugins for logging, tasks, and HAR generation.
466
+ * Configures terminal reporting, XLSX parsing, and HTTP archive recording.
467
+ */
468
+ const setupPlugins = (on, config, logWriter, installHarGenerator) => {
469
+ /* ---- BEGIN: Logging setup ---- */
470
+ // Read options https://github.com/archfz/cypress-terminal-report
471
+ const options = {
472
+ printLogsToFile: "always", // Ensures logs are always printed to a file
473
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
474
+ collectTestLogs: (context, logs) => {
475
+ const testName = fileNameBuilder(context.test, context.state);
476
+ createLogFile(config.nxRoot, config.logsFolder, testName, logs, logWriter);
477
+ },
478
+ };
479
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
480
+ require("cypress-terminal-report/src/installLogsPrinter")(on, options);
481
+ /* ---- END: Logging setup ---- */
482
+ /* ---- BEGIN: Task setup ---- */
483
+ on("task", {
484
+ parseXlsx(filePath) {
485
+ return new Promise((resolve, reject) => {
486
+ try {
487
+ const jsonData = nodeXlsx.parse(fs.readFileSync(filePath));
488
+ resolve(jsonData);
489
+ }
490
+ catch (e) {
491
+ reject(e);
492
+ }
493
+ });
494
+ },
495
+ fileExists(filename) {
496
+ return fs.existsSync(filename);
497
+ },
498
+ });
499
+ /* ---- END: Task setup ---- */
500
+ /* ---- BEGIN: codeowner setup ---- */
501
+ const codeowner = toShortTeamName(getCodeowner(config.projectRoot, config.nxRoot));
502
+ config.env.codeowner = codeowner;
503
+ /* ---- END: codeowner setup ---- */
504
+ /* ---- BEGIN: HAR setup ---- */
505
+ // Installing the HAR geneartor should happen last according to the documentation
506
+ // https://github.com/NeuraLegion/cypress-har-generator?tab=readme-ov-file#setting-up-the-plugin
507
+ installHarGenerator(on);
508
+ /* ---- END: HAR setup ---- */
509
+ return config;
510
+ };
511
+
139
512
  /* eslint-disable @typescript-eslint/no-explicit-any */
140
513
  /**
141
514
  * Sets up HAR (HTTP Archive) recording for E2E tests.
142
515
  * Records network activity and saves HAR files for failed tests.
143
516
  */
144
517
  function setupHarRecording() {
518
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
519
+ require("@neuralegion/cypress-har-generator/commands");
145
520
  beforeEach(() => {
146
521
  const harDir = Cypress.env("hars_folders");
147
522
  cy.recordHar({ rootDir: harDir });
@@ -149,7 +524,7 @@ function setupHarRecording() {
149
524
  afterEach(function () {
150
525
  if (this.currentTest.state === "failed") {
151
526
  const harDir = Cypress.env("hars_folders");
152
- const testName = fileNameBuilder.fileNameBuilder(`${Cypress.currentTest.titlePath[0]} - ${Cypress.currentTest.title}`, "failed", Cypress.currentRetry);
527
+ const testName = fileNameBuilder(`${Cypress.currentTest.titlePath[0]} - ${Cypress.currentTest.title}`, "failed", Cypress.currentRetry);
153
528
  cy.saveHar({ outDir: harDir, fileName: testName });
154
529
  }
155
530
  });
@@ -160,7 +535,8 @@ function setupHarRecording() {
160
535
  */
161
536
  function setupE2E() {
162
537
  setupHarRecording();
163
- installLogsCollector({
538
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
539
+ require("cypress-terminal-report/src/installLogsCollector")({
164
540
  xhr: {
165
541
  printHeaderData: true,
166
542
  printRequestData: true,
@@ -174,7 +550,7 @@ function setupE2E() {
174
550
  return false;
175
551
  });
176
552
  }
177
- const originalDescribe = globalThis.describe;
553
+ const originalDescribe = global.describe;
178
554
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
179
555
  if (originalDescribe) {
180
556
  const codeowner = Cypress.env("codeowner");
@@ -191,9 +567,13 @@ if (originalDescribe) {
191
567
  return originalDescribe.skip(addOwnerToTitle(title), fn);
192
568
  };
193
569
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
194
- globalThis.describe = patchedDescribe;
570
+ global.describe = patchedDescribe;
195
571
  }
196
572
 
573
+ exports.createLogFile = createLogFile;
574
+ exports.defaultCypressConfig = defaultCypressConfig;
197
575
  exports.setupDefaultCommands = setupDefaultCommands;
198
576
  exports.setupE2E = setupE2E;
199
577
  exports.setupHarRecording = setupHarRecording;
578
+ exports.setupPlugins = setupPlugins;
579
+ exports.writeFileWithPrettier = writeFileWithPrettier;