-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsetup.ts
More file actions
66 lines (59 loc) · 2.03 KB
/
setup.ts
File metadata and controls
66 lines (59 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import type { Page } from 'playwright-core';
import { z } from 'zod/v4';
import {
convertAsyncZodFunctionToSchema,
validateAsync,
} from '@code-pushup/models';
import { fileExists, logger } from '@code-pushup/utils';
const setupFunctionSchema = convertAsyncZodFunctionToSchema(
z.function({
input: [z.custom<Page>(val => val != null && typeof val === 'object')],
output: z.void(),
}),
).meta({
title: 'SetupFunction',
description: 'Async function that authenticates using a Playwright Page',
});
export type SetupFunction = z.infer<typeof setupFunctionSchema>;
const setupScriptModuleSchema = z
.object({ default: setupFunctionSchema })
.meta({
title: 'SetupScriptModule',
description:
'ES module with a default export containing the authentication setup function',
});
/** Loads and validates a setup script module from the given path. */
export async function loadSetupScript(
setupScript: string,
): Promise<SetupFunction> {
const absolutePath = path.isAbsolute(setupScript)
? setupScript
: path.join(process.cwd(), setupScript);
if (!(await fileExists(absolutePath))) {
throw new Error(`Setup script not found: ${absolutePath}`);
}
const validModule = await logger.task(
`Loading setup script from ${absolutePath}`,
async () => {
const url = pathToFileURL(absolutePath).toString();
const module: unknown = await import(url);
const validated = await validateAsync(setupScriptModuleSchema, module, {
filePath: absolutePath,
});
return { message: 'Setup script loaded successfully', result: validated };
},
);
return validModule.default;
}
/** Executes the setup function with the provided Playwright page. */
export async function runSetup(
setupFn: SetupFunction,
page: Page,
): Promise<void> {
await logger.task('Running authentication setup script', async () => {
await setupFn(page);
return { message: 'Authentication setup completed', result: undefined };
});
}