@empiricalrun/playwright-utils 0.6.3 → 0.7.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,351 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.resolveImportSpecifierExtension = exports.fileIsModule = exports.normalizeAndSaveAttachment = exports.resolveReporterOutputPath = exports.getPackageJsonPath = exports.callLogText = exports.debugTest = exports.getContainedPath = exports.sanitizeFilePathBeforeExtension = exports.addSuffixToFilePath = exports.trimLongString = exports.windowsFilesystemFriendlyLength = exports.expectTypes = exports.errorWithFile = exports.formatLocation = exports.relativeFilePath = exports.forceRegExp = exports.mergeObjects = exports.createTitleMatcher = exports.createFileMatcher = exports.createFileMatcherFromArguments = exports.createFileFiltersFromArguments = exports.serializeError = exports.filteredStackTrace = exports.filterStackFile = exports.filterStackTrace = void 0;
22
+ const fs_1 = __importDefault(require("fs"));
23
+ const path_1 = __importDefault(require("path"));
24
+ const utils_1 = require("playwright-core/lib/utils");
25
+ const utilsBundle_1 = require("playwright-core/lib/utilsBundle");
26
+ const url_1 = __importDefault(require("url"));
27
+ const util_1 = __importDefault(require("util"));
28
+ const PLAYWRIGHT_TEST_PATH = path_1.default.join(__dirname, "..");
29
+ const PLAYWRIGHT_CORE_PATH = path_1.default.dirname(require.resolve("playwright-core/package.json"));
30
+ function filterStackTrace(e) {
31
+ const name = e.name ? e.name + ": " : "";
32
+ // if (process.env.PWDEBUGIMPL)
33
+ // return { message: name + e.message, stack: e.stack || "" };
34
+ const stackLines = (0, utils_1.stringifyStackFrames)(filteredStackTrace(e.stack?.split("\n") || []));
35
+ return {
36
+ message: name + e.message,
37
+ // @ts-ignore - not able to get types from playwright-core
38
+ stack: `${name}${e.message}${stackLines.map((line) => "\n" + line).join("")}`,
39
+ };
40
+ }
41
+ exports.filterStackTrace = filterStackTrace;
42
+ function filterStackFile(file) {
43
+ if ( /*!process.env.PWDEBUGIMPL &&*/file.startsWith(PLAYWRIGHT_TEST_PATH))
44
+ return false;
45
+ if ( /*!process.env.PWDEBUGIMPL &&*/file.startsWith(PLAYWRIGHT_CORE_PATH))
46
+ return false;
47
+ return true;
48
+ }
49
+ exports.filterStackFile = filterStackFile;
50
+ function filteredStackTrace(rawStack) {
51
+ const frames = [];
52
+ for (const line of rawStack) {
53
+ const frame = (0, utilsBundle_1.parseStackTraceLine)(line);
54
+ if (!frame || !frame.file)
55
+ continue;
56
+ if (!filterStackFile(frame.file))
57
+ continue;
58
+ frames.push(frame);
59
+ }
60
+ return frames;
61
+ }
62
+ exports.filteredStackTrace = filteredStackTrace;
63
+ function serializeError(error) {
64
+ if (error instanceof Error)
65
+ return filterStackTrace(error);
66
+ return {
67
+ value: util_1.default.inspect(error),
68
+ };
69
+ }
70
+ exports.serializeError = serializeError;
71
+ function createFileFiltersFromArguments(args) {
72
+ return args.map((arg) => {
73
+ const match = /^(.*?):(\d+):?(\d+)?$/.exec(arg);
74
+ // !!ARUSH
75
+ return {
76
+ re: forceRegExp(match ? (match[1] ?? "") : arg),
77
+ line: match ? parseInt(match[2] ?? "", 10) : null,
78
+ column: match?.[3] ? parseInt(match[3], 10) : null,
79
+ };
80
+ });
81
+ }
82
+ exports.createFileFiltersFromArguments = createFileFiltersFromArguments;
83
+ function createFileMatcherFromArguments(args) {
84
+ const filters = createFileFiltersFromArguments(args);
85
+ return createFileMatcher(filters.map((filter) => filter.re || filter.exact || ""));
86
+ }
87
+ exports.createFileMatcherFromArguments = createFileMatcherFromArguments;
88
+ function createFileMatcher(patterns) {
89
+ const reList = [];
90
+ const filePatterns = [];
91
+ for (const pattern of Array.isArray(patterns) ? patterns : [patterns]) {
92
+ // @empiricalrun
93
+ if ((0, utils_1.isRegExp)(pattern) && typeof pattern !== "string") {
94
+ reList.push(pattern);
95
+ }
96
+ else {
97
+ // @empiricalrun
98
+ if (typeof pattern !== "string")
99
+ continue;
100
+ if (!pattern.startsWith("**/"))
101
+ filePatterns.push("**/" + pattern);
102
+ else
103
+ filePatterns.push(pattern);
104
+ }
105
+ }
106
+ return (filePath) => {
107
+ for (const re of reList) {
108
+ re.lastIndex = 0;
109
+ if (re.test(filePath))
110
+ return true;
111
+ }
112
+ // Windows might still receive unix style paths from Cygwin or Git Bash.
113
+ // Check against the file url as well.
114
+ if (path_1.default.sep === "\\") {
115
+ const fileURL = url_1.default.pathToFileURL(filePath).href;
116
+ for (const re of reList) {
117
+ re.lastIndex = 0;
118
+ if (re.test(fileURL))
119
+ return true;
120
+ }
121
+ }
122
+ for (const pattern of filePatterns) {
123
+ if ((0, utilsBundle_1.minimatch)(filePath, pattern, { nocase: true, dot: true }))
124
+ return true;
125
+ }
126
+ return false;
127
+ };
128
+ }
129
+ exports.createFileMatcher = createFileMatcher;
130
+ function createTitleMatcher(patterns) {
131
+ const reList = Array.isArray(patterns) ? patterns : [patterns];
132
+ return (value) => {
133
+ for (const re of reList) {
134
+ re.lastIndex = 0;
135
+ if (re.test(value))
136
+ return true;
137
+ }
138
+ return false;
139
+ };
140
+ }
141
+ exports.createTitleMatcher = createTitleMatcher;
142
+ function mergeObjects(a, b, c) {
143
+ const result = { ...a };
144
+ for (const x of [b, c].filter(Boolean)) {
145
+ for (const [name, value] of Object.entries(x)) {
146
+ if (!Object.is(value, undefined))
147
+ result[name] = value;
148
+ }
149
+ }
150
+ return result;
151
+ }
152
+ exports.mergeObjects = mergeObjects;
153
+ function forceRegExp(pattern) {
154
+ const match = pattern.match(/^\/(.*)\/([gi]*)$/);
155
+ // @empiricalrun
156
+ if (match)
157
+ return new RegExp(match[1] ?? "", match[2]);
158
+ return new RegExp(pattern, "gi");
159
+ }
160
+ exports.forceRegExp = forceRegExp;
161
+ function relativeFilePath(file) {
162
+ if (!path_1.default.isAbsolute(file))
163
+ return file;
164
+ return path_1.default.relative(process.cwd(), file);
165
+ }
166
+ exports.relativeFilePath = relativeFilePath;
167
+ function formatLocation(location) {
168
+ return (relativeFilePath(location.file) +
169
+ ":" +
170
+ location.line +
171
+ ":" +
172
+ location.column);
173
+ }
174
+ exports.formatLocation = formatLocation;
175
+ function errorWithFile(file, message) {
176
+ return new Error(`${relativeFilePath(file)}: ${message}`);
177
+ }
178
+ exports.errorWithFile = errorWithFile;
179
+ function expectTypes(receiver, types, matcherName) {
180
+ if (typeof receiver !== "object" ||
181
+ !types.includes(receiver.constructor.name)) {
182
+ const commaSeparated = types.slice();
183
+ const lastType = commaSeparated.pop();
184
+ const typesString = commaSeparated.length
185
+ ? commaSeparated.join(", ") + " or " + lastType
186
+ : lastType;
187
+ throw new Error(`${matcherName} can be only used with ${typesString} object${types.length > 1 ? "s" : ""}`);
188
+ }
189
+ }
190
+ exports.expectTypes = expectTypes;
191
+ exports.windowsFilesystemFriendlyLength = 60;
192
+ function trimLongString(s, length = 100) {
193
+ if (s.length <= length)
194
+ return s;
195
+ const hash = (0, utils_1.calculateSha1)(s);
196
+ const middle = `-${hash.substring(0, 5)}-`;
197
+ const start = Math.floor((length - middle.length) / 2);
198
+ const end = length - middle.length - start;
199
+ return s.substring(0, start) + middle + s.slice(-end);
200
+ }
201
+ exports.trimLongString = trimLongString;
202
+ function addSuffixToFilePath(filePath, suffix) {
203
+ const ext = path_1.default.extname(filePath);
204
+ const base = filePath.substring(0, filePath.length - ext.length);
205
+ return base + suffix + ext;
206
+ }
207
+ exports.addSuffixToFilePath = addSuffixToFilePath;
208
+ function sanitizeFilePathBeforeExtension(filePath) {
209
+ const ext = path_1.default.extname(filePath);
210
+ const base = filePath.substring(0, filePath.length - ext.length);
211
+ return (0, utils_1.sanitizeForFilePath)(base) + ext;
212
+ }
213
+ exports.sanitizeFilePathBeforeExtension = sanitizeFilePathBeforeExtension;
214
+ /**
215
+ * Returns absolute path contained within parent directory.
216
+ */
217
+ function getContainedPath(parentPath, subPath = "") {
218
+ const resolvedPath = path_1.default.resolve(parentPath, subPath);
219
+ if (resolvedPath === parentPath ||
220
+ resolvedPath.startsWith(parentPath + path_1.default.sep))
221
+ return resolvedPath;
222
+ return null;
223
+ }
224
+ exports.getContainedPath = getContainedPath;
225
+ exports.debugTest = (0, utilsBundle_1.debug)("pw:test");
226
+ exports.callLogText = utils_1.formatCallLog;
227
+ const folderToPackageJsonPath = new Map();
228
+ function getPackageJsonPath(folderPath) {
229
+ const cached = folderToPackageJsonPath.get(folderPath);
230
+ if (cached !== undefined)
231
+ return cached;
232
+ const packageJsonPath = path_1.default.join(folderPath, "package.json");
233
+ if (fs_1.default.existsSync(packageJsonPath)) {
234
+ folderToPackageJsonPath.set(folderPath, packageJsonPath);
235
+ return packageJsonPath;
236
+ }
237
+ const parentFolder = path_1.default.dirname(folderPath);
238
+ if (folderPath === parentFolder) {
239
+ folderToPackageJsonPath.set(folderPath, "");
240
+ return "";
241
+ }
242
+ const result = getPackageJsonPath(parentFolder);
243
+ folderToPackageJsonPath.set(folderPath, result);
244
+ return result;
245
+ }
246
+ exports.getPackageJsonPath = getPackageJsonPath;
247
+ function resolveReporterOutputPath(defaultValue, configDir, configValue) {
248
+ if (configValue)
249
+ return path_1.default.resolve(configDir, configValue);
250
+ let basePath = getPackageJsonPath(configDir);
251
+ basePath = basePath ? path_1.default.dirname(basePath) : process.cwd();
252
+ return path_1.default.resolve(basePath, defaultValue);
253
+ }
254
+ exports.resolveReporterOutputPath = resolveReporterOutputPath;
255
+ async function normalizeAndSaveAttachment(outputPath, name, options = {}) {
256
+ if (options.path === undefined && options.body === undefined)
257
+ return { name, contentType: "text/plain" };
258
+ if ((options.path !== undefined ? 1 : 0) +
259
+ (options.body !== undefined ? 1 : 0) !==
260
+ 1)
261
+ throw new Error(`Exactly one of "path" and "body" must be specified`);
262
+ if (options.path !== undefined) {
263
+ const hash = (0, utils_1.calculateSha1)(options.path);
264
+ if (!(0, utils_1.isString)(name))
265
+ throw new Error('"name" should be string.');
266
+ const sanitizedNamePrefix = (0, utils_1.sanitizeForFilePath)(name) + "-";
267
+ const dest = path_1.default.join(outputPath, "attachments", sanitizedNamePrefix + hash + path_1.default.extname(options.path));
268
+ await fs_1.default.promises.mkdir(path_1.default.dirname(dest), { recursive: true });
269
+ await fs_1.default.promises.copyFile(options.path, dest);
270
+ const contentType = options.contentType ??
271
+ (utilsBundle_1.mime.getType(path_1.default.basename(options.path)) || "application/octet-stream");
272
+ return { name, contentType, path: dest };
273
+ }
274
+ else {
275
+ const contentType = options.contentType ??
276
+ (typeof options.body === "string"
277
+ ? "text/plain"
278
+ : "application/octet-stream");
279
+ return {
280
+ name,
281
+ contentType,
282
+ body: typeof options.body === "string"
283
+ ? Buffer.from(options.body)
284
+ : options.body,
285
+ };
286
+ }
287
+ }
288
+ exports.normalizeAndSaveAttachment = normalizeAndSaveAttachment;
289
+ function fileIsModule(file) {
290
+ if (file.endsWith(".mjs") || file.endsWith(".mts"))
291
+ return true;
292
+ if (file.endsWith(".cjs") || file.endsWith(".cts"))
293
+ return false;
294
+ const folder = path_1.default.dirname(file);
295
+ return folderIsModule(folder);
296
+ }
297
+ exports.fileIsModule = fileIsModule;
298
+ function folderIsModule(folder) {
299
+ const packageJsonPath = getPackageJsonPath(folder);
300
+ if (!packageJsonPath)
301
+ return false;
302
+ // Rely on `require` internal caching logic.
303
+ return require(packageJsonPath).type === "module";
304
+ }
305
+ // This follows the --moduleResolution=bundler strategy from tsc.
306
+ // https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#moduleresolution-bundler
307
+ const kExtLookups = new Map([
308
+ [".js", [".jsx", ".ts", ".tsx"]],
309
+ [".jsx", [".tsx"]],
310
+ [".cjs", [".cts"]],
311
+ [".mjs", [".mts"]],
312
+ ["", [".js", ".ts", ".jsx", ".tsx", ".cjs", ".mjs", ".cts", ".mts"]],
313
+ ]);
314
+ function resolveImportSpecifierExtension(resolved, isPathMapping, isESM) {
315
+ if (fileExists(resolved))
316
+ return resolved;
317
+ for (const [ext, others] of kExtLookups) {
318
+ if (!resolved.endsWith(ext))
319
+ continue;
320
+ for (const other of others) {
321
+ const modified = resolved.substring(0, resolved.length - ext.length) + other;
322
+ if (fileExists(modified))
323
+ return modified;
324
+ }
325
+ break; // Do not try '' when a more specific extension like '.jsx' matched.
326
+ }
327
+ // After TypeScript path mapping, here's how directories with a `package.json` are resolved:
328
+ // - `package.json#exports` is not respected
329
+ // - `package.json#main` is respected only in CJS mode
330
+ // - `index.js` default is respected only in CJS mode
331
+ //
332
+ // More info:
333
+ // - https://www.typescriptlang.org/docs/handbook/modules/reference.html#paths-should-not-point-to-monorepo-packages-or-node_modules-packages
334
+ // - https://www.typescriptlang.org/docs/handbook/modules/reference.html#directory-modules-index-file-resolution
335
+ // - https://nodejs.org/dist/latest-v20.x/docs/api/modules.html#folders-as-modules
336
+ const shouldNotResolveDirectory = isPathMapping && isESM;
337
+ if (!shouldNotResolveDirectory && dirExists(resolved)) {
338
+ // If we import a package, let Node.js figure out the correct import based on package.json.
339
+ if (fileExists(path_1.default.join(resolved, "package.json")))
340
+ return resolved;
341
+ const dirImport = path_1.default.join(resolved, "index");
342
+ return resolveImportSpecifierExtension(dirImport, isPathMapping, isESM);
343
+ }
344
+ }
345
+ exports.resolveImportSpecifierExtension = resolveImportSpecifierExtension;
346
+ function fileExists(resolved) {
347
+ return fs_1.default.statSync(resolved, { throwIfNoEntry: false })?.isFile();
348
+ }
349
+ function dirExists(resolved) {
350
+ return fs_1.default.statSync(resolved, { throwIfNoEntry: false })?.isDirectory();
351
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@empiricalrun/playwright-utils",
3
- "version": "0.6.3",
3
+ "version": "0.7.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"
@@ -21,13 +21,6 @@
21
21
  "url": "https://github.com/empirical-run/empirical.git"
22
22
  },
23
23
  "author": "Empirical Team <hey@empirical.run>",
24
- "devDependencies": {
25
- "@playwright/test": "^1.44.1",
26
- "@types/node": "^20.14.9"
27
- },
28
- "dependencies": {
29
- "mailosaur": "^8.6.1"
30
- },
31
24
  "scripts": {
32
25
  "dev": "tsc --build --watch",
33
26
  "build": "tsc --build && node ./../../tools/static-env-vars.js dist",
@@ -35,5 +28,21 @@
35
28
  "lint": "eslint .",
36
29
  "test": "vitest run",
37
30
  "test:watch": "vitest"
31
+ },
32
+ "devDependencies": {
33
+ "@playwright/test": "^1.44.1",
34
+ "@types/node": "^20.14.9"
35
+ },
36
+ "dependencies": {
37
+ "@aws-sdk/client-s3": "^3.614.0",
38
+ "@aws-sdk/s3-request-presigner": "^3.614.0",
39
+ "@babel/code-frame": "^7.24.7",
40
+ "@types/babel__code-frame": "^7.0.6",
41
+ "@types/md5": "^2.3.5",
42
+ "@types/mime": "3.0.0",
43
+ "mailosaur": "^8.6.1",
44
+ "md5": "^2.3.0",
45
+ "mime": "3.0.0",
46
+ "playwright-core": "^1.46.1"
38
47
  }
39
- }
48
+ }