Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeModule from "node:module";
4import * as NodePath from "node:path";
5import * as NodeVM from "node:vm";
6
7import * as Effect from "effect/Effect";
8import * as Schema from "effect/Schema";
9
10const require = NodeModule.createRequire(import.meta.url);
11const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
12const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
13const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
14const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
15const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
16const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
17const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
18const PLAYWRIGHT_BROWSER_NAME = "chromium";
19
20export class PlaywrightPackageResolveError extends Schema.TaggedError<PlaywrightPackageResolveError>()(
21 "PlaywrightPackageResolveError",
22 {
23 specifier: Schema.String,
24 cause: Schema.Defect(),
25 },
26) {
27 override get message(): string {
28 return `Failed to resolve Playwright package: ${this.specifier}`;
29 }
30}
31
32export class PlaywrightCoreBundleReadError extends Schema.TaggedError<PlaywrightCoreBundleReadError>()(
33 "PlaywrightCoreBundleReadError",
34 {
35 bundlePath: Schema.String,
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Failed to read Playwright core bundle: ${this.bundlePath}`;
41 }
42}
43
44export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedError<PlaywrightSourceMarkerNotFoundError>()(
45 "PlaywrightSourceMarkerNotFoundError",
46 {
47 bundlePath: Schema.String,
48 marker: Schema.String,
49 },
50) {
51 override get message(): string {
52 return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
53 }
54}
55
56export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedError<PlaywrightSourceTerminatorNotFoundError>()(
57 "PlaywrightSourceTerminatorNotFoundError",
58 {
59 bundlePath: Schema.String,
60 terminator: Schema.String,
61 },
62) {
63 override get message(): string {
64 return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
65 }
66}
67
68export class PlaywrightSourceEvaluationError extends Schema.TaggedError<PlaywrightSourceEvaluationError>()(
69 "PlaywrightSourceEvaluationError",
70 {
71 bundlePath: Schema.String,
72 timeoutMs: Schema.Number,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
78 }
79}
80
81export class PlaywrightSourceValidationError extends Schema.TaggedError<PlaywrightSourceValidationError>()(
82 "PlaywrightSourceValidationError",
83 {
84 bundlePath: Schema.String,
85 actualType: Schema.String,
86 actualLength: Schema.NullOr(Schema.Number),
87 minimumLength: Schema.Number,
88 },
89) {
90 override get message(): string {
91 const actual =
92 this.actualLength === null
93 ? this.actualType
94 : `${this.actualType} with ${this.actualLength} characters`;
95 return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
96 }
97}
98
99export class PlaywrightOptionsEncodeError extends Schema.TaggedError<PlaywrightOptionsEncodeError>()(
100 "PlaywrightOptionsEncodeError",
101 {
102 sdkLanguage: Schema.String,
103 browserName: Schema.String,
104 cause: Schema.Defect(),
105 },
106) {
107 override get message(): string {
108 return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
109 }
110}
111
112export const PlaywrightInjectedRuntimeError = Schema.Union([
113 PlaywrightPackageResolveError,
114 PlaywrightCoreBundleReadError,
115 PlaywrightSourceMarkerNotFoundError,
116 PlaywrightSourceTerminatorNotFoundError,
117 PlaywrightSourceEvaluationError,
118 PlaywrightSourceValidationError,
119 PlaywrightOptionsEncodeError,
120]);
121export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
122
123export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
124 "PlaywrightInjectedRuntime.extractSource",
125)(function* (coreBundle: string, bundlePath: string) {
126 const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
127 if (start < 0) {
128 return yield* new PlaywrightSourceMarkerNotFoundError({
129 bundlePath,
130 marker: PLAYWRIGHT_SOURCE_MARKER,
131 });
132 }
133 const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
134 const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
135 if (literalEnd < 0) {
136 return yield* new PlaywrightSourceTerminatorNotFoundError({
137 bundlePath,
138 terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
139 });
140 }
141 const literal = coreBundle.slice(literalStart, literalEnd);
142 const source = yield* Effect.try({
143 try: () =>
144 NodeVM.runInNewContext(literal, Object.create(null), {
145 timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
146 }),
147 catch: (cause) =>
148 new PlaywrightSourceEvaluationError({
149 bundlePath,
150 timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
151 cause,
152 }),
153 });
154 if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
155 return yield* new PlaywrightSourceValidationError({
156 bundlePath,
157 actualType: typeof source,
158 actualLength: typeof source === "string" ? source.length : null,
159 minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
160 });
161 }
162 return source;
163});
164
165export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
166 function* () {
167 const packageJsonPath = yield* Effect.try({
168 try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
169 catch: (cause) =>
170 new PlaywrightPackageResolveError({
171 specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
172 cause,
173 }),
174 });
175 const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
176 const coreBundle = yield* Effect.tryPromise({
177 try: () => NodeFSP.readFile(bundlePath, "utf8"),
178 catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
179 });
180 return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
181 },
182);
183
184export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
185 "PlaywrightInjectedRuntime.installExpression",
186)(function* () {
187 const source = yield* playwrightInjectedRuntimeSource();
188 const options = yield* encodeUnknownJson({
189 isUnderTest: false,
190 sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
191 testIdAttributeName: "data-testid",
192 stableRafCount: 1,
193 browserName: PLAYWRIGHT_BROWSER_NAME,
194 shouldPrependErrorPrefix: false,
195 isUtilityWorld: false,
196 customEngines: [],
197 }).pipe(
198 Effect.mapError(
199 (cause) =>
200 new PlaywrightOptionsEncodeError({
201 sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
202 browserName: PLAYWRIGHT_BROWSER_NAME,
203 cause,
204 }),
205 ),
206 );
207 return `(() => {
208 if (globalThis.__t3PlaywrightInjected) return true;
209 const module = { exports: {} };
210 ${source}
211 globalThis.__t3PlaywrightInjected = new (module.exports.InjectedScript())(globalThis, ${options});
212 return true;
213 })()`;
214});