-
Notifications
You must be signed in to change notification settings - Fork 460
Expand file tree
/
Copy pathapplication.ts
More file actions
264 lines (243 loc) · 9.75 KB
/
Copy pathapplication.ts
File metadata and controls
264 lines (243 loc) · 9.75 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import * as path from 'node:path';
import { parsePublishableKey } from '@clerk/shared/keys';
import { clerkSetup } from '@clerk/testing/playwright';
import { awaitableTreekill, createLogger, fs, getPort, run, waitForIdleProcess, waitForServer } from '../scripts';
import type { ApplicationConfig } from './applicationConfig.js';
import type { EnvironmentConfig } from './environment.js';
export type Application = ReturnType<typeof application>;
/**
* Resolves the server URL for a dev/serve process, ensuring the runtime port
* is always reflected in the URL. Uses the URL constructor to detect whether
* an explicit port is present (avoiding false positives from the scheme colon).
*/
export const resolveServerUrl = (
optsServerUrl: string | undefined,
fallbackServerUrl: string | undefined,
port: number,
): string => {
if (optsServerUrl) {
try {
const parsed = new URL(optsServerUrl);
if (!parsed.port) {
parsed.port = String(port);
}
return parsed.origin;
} catch {
// Bare host (e.g. "localhost"), not a full URL
return `${optsServerUrl}:${port}`;
}
}
return fallbackServerUrl || `http://localhost:${port}`;
};
export const createAppRuntimeEnv = (env?: EnvironmentConfig): Record<string, string> => {
if (!env?.publicVariables || !env?.privateVariables) {
return {};
}
const runtimeEnv: Record<string, string> = {};
// Private variables intentionally win when the same runtime key exists in both maps.
for (const [key, value] of [...env.publicVariables, ...env.privateVariables]) {
if (value === undefined || value === null) {
continue;
}
runtimeEnv[key] = String(value);
}
return runtimeEnv;
};
export const application = (
config: ApplicationConfig,
appDirPath: string,
appDirName: string,
serverUrl: string | undefined,
) => {
const { name, scripts, envWriter, copyKeylessToEnv } = config;
const logger = createLogger({ prefix: `${appDirName}` });
const state = { completedSetup: false, serverUrl: '', env: {} as EnvironmentConfig, lastDevPort: 0 };
const cleanupFns: { (): unknown }[] = [];
const now = Date.now();
const stdoutFilePath = path.resolve(appDirPath, `e2e.${now}.log`);
const stderrFilePath = path.resolve(appDirPath, `e2e.${now}.err.log`);
let buildOutput = '';
let serveOutput = '';
const self = {
name,
scripts,
appDir: appDirPath,
get serverUrl() {
return state.serverUrl;
},
get env() {
return state.env;
},
withEnv: async (env: EnvironmentConfig) => {
state.env = env;
return envWriter(appDirPath, env);
},
keylessToEnv: async () => {
return copyKeylessToEnv(appDirPath);
},
setup: async (opts?: { strategy?: 'ci' | 'i' | 'copy'; force?: boolean }) => {
const { force } = opts || {};
const nodeModulesExist = await fs.pathExists(path.resolve(appDirPath, 'node_modules'));
if (force || !nodeModulesExist) {
const log = logger.child({ prefix: 'setup' }).info;
// Use pkglab add to install packages from the local registry,
// unless E2E_SDK_SOURCE=latest which installs from npm instead
const pkglabDeps = config.pkglabDependencies;
if (pkglabDeps.length > 0 && process.env.E2E_SDK_SOURCE !== 'latest') {
await run(`pkglab add ${pkglabDeps.join(' ')}`, { cwd: appDirPath, log });
} else {
await run(scripts.setup, { cwd: appDirPath, log });
}
state.completedSetup = true;
// Print all Clerk package versions (direct and transitive)
const clerkPackagesLog = logger.child({ prefix: 'clerk-packages' }).info;
clerkPackagesLog('Installed @clerk/* packages:');
await run('pnpm list @clerk/* --depth 100', { cwd: appDirPath, log: clerkPackagesLog });
}
},
dev: async (opts: { port?: number; manualStart?: boolean; detached?: boolean; serverUrl?: string } = {}) => {
const log = logger.child({ prefix: 'dev' }).info;
const port = opts.port || (await getPort());
const runtimeServerUrl = resolveServerUrl(opts.serverUrl, serverUrl, port);
log(`Will try to serve app at ${runtimeServerUrl}`);
if (opts.manualStart) {
// for debugging, you can start the dev server manually by cd'ing into the temp dir
// and running the corresponding dev command
// this allows the test to run as normally, while setup is controlled by you,
// so you can inspect the running up outside the PW lifecycle
state.serverUrl = runtimeServerUrl;
return { port, serverUrl: runtimeServerUrl };
}
const proc = run(scripts.dev, {
cwd: appDirPath,
env: { ...createAppRuntimeEnv(state.env), PORT: port.toString() },
detached: opts.detached,
stdout: opts.detached ? fs.openSync(stdoutFilePath, 'a') : undefined,
stderr: opts.detached ? fs.openSync(stderrFilePath, 'a') : undefined,
log: opts.detached ? undefined : log,
});
const shouldExit = () => !!proc.exitCode && proc.exitCode !== 0;
await waitForServer(runtimeServerUrl, { log, maxAttempts: Infinity, shouldExit });
log(`Server started at ${runtimeServerUrl}, pid: ${proc.pid}`);
cleanupFns.push(() => awaitableTreekill(proc.pid, 'SIGKILL'));
state.serverUrl = runtimeServerUrl;
// Setup Clerk testing tokens after the server is running
if (state.env) {
try {
const publishableKey = state.env.publicVariables.get('CLERK_PUBLISHABLE_KEY');
const secretKey = state.env.privateVariables.get('CLERK_SECRET_KEY');
const apiUrl = state.env.privateVariables.get('CLERK_API_URL');
if (publishableKey && secretKey) {
const { instanceType, frontendApi: frontendApiUrl } = parsePublishableKey(publishableKey);
if (instanceType !== 'development') {
log('Skipping clerkSetup for non-development instance');
} else {
await clerkSetup({
publishableKey,
frontendApiUrl,
secretKey,
// @ts-expect-error apiUrl is not a typed option for clerkSetup, but it is accepted at runtime.
apiUrl,
dotenv: false,
});
log('Clerk testing tokens setup complete');
}
}
} catch (error) {
logger.warn('Failed to setup Clerk testing tokens:', error);
}
}
state.lastDevPort = port;
return { port, serverUrl: runtimeServerUrl, pid: proc.pid };
},
restart: async () => {
const log = logger.child({ prefix: 'restart' }).info;
log('Restarting dev server...');
await self.stop();
return self.dev({ port: state.lastDevPort });
},
build: async () => {
const log = logger.child({ prefix: 'build' }).info;
await run(scripts.build, {
cwd: appDirPath,
env: createAppRuntimeEnv(state.env),
log: (msg: string) => {
buildOutput += `\n${msg}`;
log(msg);
},
});
},
get buildOutput() {
return buildOutput;
},
get serveOutput() {
return serveOutput;
},
serve: async (opts: { port?: number; manualStart?: boolean; detached?: boolean; serverUrl?: string } = {}) => {
const log = logger.child({ prefix: 'serve' }).info;
const port = opts.port || (await getPort());
const runtimeServerUrl = resolveServerUrl(opts.serverUrl, serverUrl, port);
log(`Will try to serve app at ${runtimeServerUrl}`);
if (opts.manualStart) {
state.serverUrl = runtimeServerUrl;
return { port, serverUrl: runtimeServerUrl };
}
// Read .env file and pass as process env vars since production servers
// may not auto-load .env files (e.g., react-router-serve)
const envFromFile: Record<string, string> = {};
const envFilePath = path.resolve(appDirPath, '.env');
if (fs.existsSync(envFilePath)) {
const envContent = fs.readFileSync(envFilePath, 'utf-8');
for (const line of envContent.split('\n')) {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#')) {
const eqIdx = trimmed.indexOf('=');
if (eqIdx > 0) {
envFromFile[trimmed.slice(0, eqIdx)] = trimmed.slice(eqIdx + 1);
}
}
}
}
const proc = run(scripts.serve, {
cwd: appDirPath,
env: { ...envFromFile, ...createAppRuntimeEnv(state.env), PORT: port.toString() },
detached: opts.detached,
stdout: opts.detached ? fs.openSync(stdoutFilePath, 'a') : undefined,
stderr: opts.detached ? fs.openSync(stderrFilePath, 'a') : undefined,
log: opts.detached
? undefined
: (msg: string) => {
serveOutput += `\n${msg}`;
log(msg);
},
});
if (opts.detached) {
const shouldExit = () => !!proc.exitCode && proc.exitCode !== 0;
await waitForServer(runtimeServerUrl, { log, maxAttempts: Infinity, shouldExit });
} else {
await waitForIdleProcess(proc);
}
log(`Server started at ${runtimeServerUrl}, pid: ${proc.pid}`);
cleanupFns.push(() => awaitableTreekill(proc.pid, 'SIGKILL'));
state.serverUrl = runtimeServerUrl;
return { port, serverUrl: runtimeServerUrl, pid: proc.pid };
},
stop: async () => {
logger.info('Stopping...');
await Promise.all(cleanupFns.map(fn => fn()));
cleanupFns.splice(0, cleanupFns.length);
state.serverUrl = '';
return new Promise(res => setTimeout(res, 2000));
},
teardown: async () => {
logger.info('Tearing down...');
await self.stop();
try {
fs.rmSync(appDirPath, { recursive: true, force: true });
} catch (e) {
console.log(e);
}
},
};
return self;
};