saffron-ai 1.0.1 → 1.2.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,1264 @@
1
+ // Written by `saffron eject`. This file is yours now: Saffron does not read
2
+ // it or keep it up to date. The specs beside it import it.
3
+ //
4
+ // It holds the few things plain Playwright does differently from a Saffron
5
+ // replay: text checks bounded at a value's edges, {date...} and {unique...}
6
+ // tokens, {env:...} values read at run time, network checks counted from the
7
+ // latest browser action, captured values that wait for the page to settle,
8
+ // browser sessions and tabs, downloads and file choosers, and API requests
9
+ // sent through a session's own request client with the checks on their
10
+ // responses.
11
+ import { createHash, randomBytes } from "node:crypto";
12
+ import dns from "node:dns";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { expect, test, type APIResponse, type Browser, type BrowserContext, type Dialog, type Download, type ElementHandle, type Locator, type Page, type Request, type Response } from "@playwright/test";
16
+
17
+ const SETTINGS: {
18
+ /** Locale and time zone {date...} tokens are written in. */
19
+ locale: string;
20
+ timeZone?: string;
21
+ /** The Saffron project, relative to this file: upload paths are its. */
22
+ projectRoot: string;
23
+ /** Storage state per browser session, relative to the project; storageState is every other session's. */
24
+ sessions: Record<string, { storageState?: string }>;
25
+ storageState?: string;
26
+ /** How long a check waits, in milliseconds. */
27
+ timeoutMs: number;
28
+ /** The APIs under test (api in saffron.config.json): the default one's base URL and the named ones'. */
29
+ api: { baseURL?: string; services: Record<string, string> };
30
+ } = /*SETTINGS*/ { locale: "en-US", projectRoot: "..", sessions: {}, timeoutMs: 10000, api: { services: {} } } /*END*/;
31
+
32
+ // --- values ---------------------------------------------------------------
33
+
34
+ /** The {env:...} values read so far, so an error message shows the token and never the value. */
35
+ const SECRETS = new Map<string, string>();
36
+
37
+ /** An {env:NAME} value, read when the test runs. A spec never holds one. Empty counts as unset: a blank check would hold for anything. */
38
+ /** A duration a recording wrote as text: milliseconds ("2000") or a number with a unit ("2 s", "500 ms", "1 m"). */
39
+ export function duration(text: string): number {
40
+ const m = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|sec|secs|second|seconds|min|mins|minute|minutes|millisecond|milliseconds)?\s*$/i.exec(text);
41
+ if (!m) throw new Error(`${JSON.stringify(text)} is not a duration: write milliseconds ("2000") or a number with a unit ("2 s", "500 ms", "1 m")`);
42
+ const unit = (m[2] ?? "ms").toLowerCase();
43
+ const factor = unit.startsWith("ms") || unit.startsWith("milli") ? 1 : unit.startsWith("m") ? 60_000 : 1000;
44
+ return Math.round(Number(m[1]) * factor);
45
+ }
46
+
47
+ export function env(name: string): string {
48
+ const value = process.env[name];
49
+ if (value === undefined || value === "") throw new Error(`environment variable ${name} is not set`);
50
+ SECRETS.set(name, value);
51
+ return value;
52
+ }
53
+
54
+ /** Every credential the API handed out in this worker (isCredentialCapture), name to value: masked like an {env:...} value. Which a request may send is the Run's own. */
55
+ const CREDENTIALS = new Map<string, string>();
56
+
57
+ /** Text with every {env:...} value and captured credential written back as its token, longest first, as written and as JSON escapes it. */
58
+ function mask(text: string): string {
59
+ const values = [...[...SECRETS].map(([name, value]) => [`{env:${name}}`, value]), ...[...CREDENTIALS].map(([name, value]) => [`{captured:${name}}`, value])];
60
+ for (const [token, value] of values.sort((a, b) => b[1].length - a[1].length)) {
61
+ if (value.length < 3) continue;
62
+ text = text.replaceAll(value, token);
63
+ const escaped = JSON.stringify(value).slice(1, -1);
64
+ if (escaped !== value) text = text.replaceAll(escaped, token);
65
+ }
66
+ return text;
67
+ }
68
+
69
+ /** Words a capture's name or its field carries when the value is a credential, as the runner reads them. */
70
+ const CREDENTIAL_WORDS = new Set(["token", "secret", "password", "passwd", "pwd", "apikey", "accesskey", "privatekey", "session", "credential", "credentials", "auth", "authorization", "jwt", "bearer", "cookie", "otp", "pin", "csrf", "xsrf", "signature", "nonce", "refresh"]);
71
+
72
+ function isCredentialCapture(name: string, pointer: string): boolean {
73
+ const words = `${name} ${pointer.split("/").at(-1) ?? ""}`.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
74
+ return words.some((w, i) => CREDENTIAL_WORDS.has(w) || (w === "key" && ["api", "access", "private", "secret"].includes(words[i - 1] ?? "")));
75
+ }
76
+
77
+ /** Whether a host name resolves to a link-local address, looked up for every request. */
78
+ async function resolvesLinkLocal(hostname: string): Promise<boolean> {
79
+ const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
80
+ if (host === "localhost" || /^[\d.]+$/.test(host) || host.includes(":")) return false;
81
+ const found = await dns.promises.lookup(host, { all: true }).catch(() => []);
82
+ return found.some((f) => isLinkLocal(f.address));
83
+ }
84
+
85
+ /** A number or boolean a request body sends where the recording holds text with tokens (a row's "<seats>"). */
86
+ export function typed(text: string, type: "number" | "boolean"): number | boolean {
87
+ if (type === "boolean") {
88
+ if (text === "true" || text === "false") return text === "true";
89
+ throw new Error(`a body field must be true or false, but its value resolves to ${JSON.stringify(mask(text))}`);
90
+ }
91
+ // A decimal number as JSON writes one, as replay reads it: "Infinity" would be sent as null, "0x1F" as 31.
92
+ const number = Number(text);
93
+ if (!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(text) || !Number.isFinite(number)) throw new Error(`a body field must be a number, but its value resolves to ${JSON.stringify(mask(text))}`);
94
+ return number;
95
+ }
96
+
97
+ /** A check's expected text must say something: "" is in every text. */
98
+ function said<T extends string | RegExp>(expected: T, what: string): T {
99
+ if (typeof expected === "string" ? normalize(expected) === "" : expected.source === "" || expected.source === "(?:)") throw new Error(`${what} is blank, so it would hold for anything`);
100
+ return expected;
101
+ }
102
+
103
+ /** A path in the Saffron project (uploads are recorded relative to it). */
104
+ export function projectFile(file: string): string {
105
+ return path.resolve(path.dirname(test.info().file), SETTINGS.projectRoot, file);
106
+ }
107
+
108
+ const LETTER = String.raw`[\p{L}\p{N}\p{M}]`;
109
+
110
+ /**
111
+ * Text that must appear inside a longer text. Where the step wrote a row or
112
+ * data value at the start or end ("Order <id>"), that edge is whole: "Order 1"
113
+ * never matches "Order 12". Elsewhere it is a plain substring, as in replay.
114
+ */
115
+ export function bounded(text: string, edges: "start" | "end" | "both", flags = "u"): RegExp {
116
+ text = said(normalize(text), "the expected text");
117
+ const start = edges !== "end" && new RegExp(`^${LETTER}`, "u").test(text);
118
+ const end = edges !== "start" && new RegExp(`${LETTER}$`, "u").test(text);
119
+ // Beside a digit, no decimal or thousands part either: "1" is not in "1.5" or "1,000".
120
+ const before = /^\p{N}/u.test(text) ? `(?<!${LETTER}|\\p{N}[.,])` : `(?<!${LETTER})`;
121
+ const after = /\p{N}$/u.test(text) ? `(?!${LETTER}|[.,]\\p{N})` : `(?!${LETTER})`;
122
+ // Quotes and `>` as hex, so Playwright reads no string or chain in the regex; any whitespace as replay's label match allows.
123
+ const body = escapeRegExp(text).replace(/ /g, "\\s+").replace(/["'`>]/g, (c) => `\\x${c.charCodeAt(0).toString(16)}`);
124
+ return new RegExp(`${start ? before : ""}${body}${end ? after : ""}`, flags);
125
+ }
126
+
127
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
128
+ const normalize = (s: string) => s.replace(/\s+/g, " ").trim();
129
+ const contains = (haystack: string, needle: string | RegExp) => (typeof needle === "string" ? haystack.includes(needle) : needle.test(haystack));
130
+
131
+ /** A recorded regular expression; unicode mode when it needs one. */
132
+ export function pattern(source: string, flags = ""): RegExp {
133
+ if (source.includes(`[\\p{L}\\p{N}\\p{M}]`) && !/[uv]/.test(flags)) flags += "u";
134
+ return new RegExp(source, flags);
135
+ }
136
+
137
+ // --- dates ----------------------------------------------------------------
138
+
139
+ const DATE_TOKEN_RE = /\{date(?:([+-]\d+)(?:([^\d{}:]+?)([+-]\d+))?)?(?::([^}]+))?\}/g;
140
+ const FIELDS = "YYYY|YY|MMMM|MMM|MM|M|DD|D|dddd|ddd";
141
+ const FIELD_RE = new RegExp(FIELDS, "g");
142
+ const LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/;
143
+
144
+ function formatOf(rest: string | undefined): { format: string; locale?: string } {
145
+ if (rest === undefined) return { format: "YYYY-MM-DD" };
146
+ const at = rest.lastIndexOf(":");
147
+ const tail = rest.slice(at + 1);
148
+ return at >= 0 && LOCALE_RE.test(tail) ? { format: rest.slice(0, at), locale: tail } : { format: rest };
149
+ }
150
+
151
+ function calendarDay(now: Date): [number, number, number] {
152
+ if (!SETTINGS.timeZone) return [now.getFullYear(), now.getMonth(), now.getDate()];
153
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone: SETTINGS.timeZone, year: "numeric", month: "numeric", day: "numeric" }).formatToParts(now);
154
+ const n = (type: string) => Number(parts.find((p) => p.type === type)!.value);
155
+ return [n("year"), n("month") - 1, n("day")];
156
+ }
157
+
158
+ const dayAt = (now: Date, offset: number) => {
159
+ const [y, m, d] = calendarDay(now);
160
+ return new Date(Date.UTC(y, m, d + offset));
161
+ };
162
+
163
+ function nameOf(d: Date, field: string, format: string, locale: string): string {
164
+ const fields: string[] = format.match(FIELD_RE) ?? [];
165
+ const type = field[0] === "M" ? "month" : "weekday";
166
+ const options: Intl.DateTimeFormatOptions = { timeZone: "UTC", calendar: "gregory", [type]: field.length === 4 ? "long" : "short" };
167
+ if (fields.some((f) => f[0] === "D")) options.day = "numeric";
168
+ if (fields.some((f) => f[0] === "Y")) options.year = "numeric";
169
+ if (type === "weekday" && fields.some((f) => f[0] === "M")) options.month = fields.includes("MMMM") ? "long" : fields.includes("MMM") ? "short" : "numeric";
170
+ return new Intl.DateTimeFormat(locale, options).formatToParts(d).find((p) => p.type === type)?.value ?? field;
171
+ }
172
+
173
+ function fieldOf(d: Date, field: string, format: string, locale: string): string {
174
+ switch (field) {
175
+ case "YYYY":
176
+ return String(d.getUTCFullYear());
177
+ case "YY":
178
+ return String(d.getUTCFullYear() % 100).padStart(2, "0");
179
+ case "MM":
180
+ return String(d.getUTCMonth() + 1).padStart(2, "0");
181
+ case "M":
182
+ return String(d.getUTCMonth() + 1);
183
+ case "DD":
184
+ return String(d.getUTCDate()).padStart(2, "0");
185
+ case "D":
186
+ return String(d.getUTCDate());
187
+ default:
188
+ return nameOf(d, field, format, locale);
189
+ }
190
+ }
191
+
192
+ const formatDay = (d: Date, format: string, locale: string) => format.replace(FIELD_RE, (field) => fieldOf(d, field, format, locale));
193
+
194
+ function formatRange(a: Date, b: Date, format: string, sep: string, locale: string): string {
195
+ const parts = format.split(new RegExp(`(${FIELDS})`));
196
+ const year = a.getUTCFullYear() !== b.getUTCFullYear();
197
+ const month = year || a.getUTCMonth() !== b.getUTCMonth();
198
+ const day = month || a.getUTCDate() !== b.getUTCDate();
199
+ const differs = (field: string) => (field[0] === "Y" ? year : field[0] === "M" ? month : day);
200
+ const at = parts.flatMap((p, i) => (i % 2 && differs(p) ? [i] : []));
201
+ if (at.length === 0) return formatDay(a, format, locale);
202
+ const render = (d: Date, from: number, to: number) => parts.slice(from, to).map((p, i) => ((from + i) % 2 ? fieldOf(d, p, format, locale) : p)).join("");
203
+ const last = at[at.length - 1];
204
+ const tail = /^[^\s,/-]*/.exec(parts[last + 1] ?? "")![0];
205
+ return `${render(a, 0, last + 1)}${tail}${sep}${render(b, at[0], parts.length)}`;
206
+ }
207
+
208
+ /** A {date...} token on `now`'s calendar, as Saffron writes it. */
209
+ export function date(token: string, now: Date): string {
210
+ return token.replace(DATE_TOKEN_RE, (_token: string, from?: string, sep?: string, to?: string, rest?: string) => {
211
+ const { format, locale = SETTINGS.locale } = formatOf(rest);
212
+ // A locale this Node.js does not know leaves the token as written, as Saffron does.
213
+ if (!LOCALE_RE.test(locale) || Intl.DateTimeFormat.supportedLocalesOf(locale).length === 0) return _token;
214
+ const start = dayAt(now, Number(from ?? 0));
215
+ return to === undefined ? formatDay(start, format, locale) : formatRange(start, dayAt(now, Number(to)), format, sep!, locale);
216
+ });
217
+ }
218
+
219
+ // --- network --------------------------------------------------------------
220
+
221
+ interface Observed {
222
+ seq: number;
223
+ requestSeq: number;
224
+ url: string;
225
+ method: string;
226
+ status: number;
227
+ body?: string;
228
+ }
229
+
230
+ /**
231
+ * The responses one browser session saw. A wait looks from the start of the
232
+ * previous step on; a check looks at requests started since the latest
233
+ * browser action, so an earlier success never answers for a later one.
234
+ */
235
+ class ResponseLog {
236
+ private entries: Observed[] = [];
237
+ private seq = 0;
238
+ private prevStepSeq = 0;
239
+ private curStepSeq = 0;
240
+ private requestSeq = 0;
241
+ private actionSeq = 0;
242
+ private requests = new WeakMap<Request, number>();
243
+ private inFlight = new Set<Request>();
244
+
245
+ constructor(context: BrowserContext) {
246
+ context.on("request", (request) => {
247
+ const previous = request.redirectedFrom();
248
+ this.requests.set(request, previous ? (this.requests.get(previous) ?? 0) : ++this.requestSeq);
249
+ if (["fetch", "xhr"].includes(request.resourceType())) this.inFlight.add(request);
250
+ });
251
+ const done = (request: Request) => void this.inFlight.delete(request);
252
+ context.on("requestfinished", done);
253
+ context.on("requestfailed", done);
254
+ context.on("response", (response: Response) => {
255
+ const entry: Observed = {
256
+ seq: ++this.seq,
257
+ requestSeq: this.requests.get(response.request()) ?? 0,
258
+ url: response.url(),
259
+ method: response.request().method(),
260
+ status: response.status(),
261
+ };
262
+ this.entries.push(entry);
263
+ if (/json|text|xml/i.test(response.headers()["content-type"] ?? "")) {
264
+ void response.text().then((body) => (entry.body = body), () => undefined);
265
+ }
266
+ });
267
+ }
268
+
269
+ markStep() {
270
+ this.prevStepSeq = this.curStepSeq;
271
+ this.curStepSeq = this.seq;
272
+ }
273
+
274
+ markAction() {
275
+ this.actionSeq = this.requestSeq;
276
+ }
277
+
278
+ sincePreviousStep = () => this.entries.filter((e) => e.seq > this.prevStepSeq);
279
+ sinceAction = () => this.entries.filter((e) => e.requestSeq > this.actionSeq);
280
+
281
+ /** Waits, up to `ms`, until no fetch or XHR request is still running. */
282
+ async quiet(ms: number) {
283
+ const until = Date.now() + ms;
284
+ await new Promise((resolve) => setTimeout(resolve, Math.min(150, ms)));
285
+ while (this.inFlight.size > 0 && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 25));
286
+ }
287
+ }
288
+
289
+ const decode = (url: string) => {
290
+ try {
291
+ return decodeURIComponent(url);
292
+ } catch {
293
+ return url;
294
+ }
295
+ };
296
+
297
+ function statusMatches(observed: number, expected?: string): boolean {
298
+ if (!expected) return observed >= 200 && observed < 300;
299
+ const cls = /^([1-5])xx$/i.exec(expected.trim());
300
+ if (cls) return observed >= Number(cls[1]) * 100 && observed < Number(cls[1]) * 100 + 100;
301
+ return observed === Number(expected.trim());
302
+ }
303
+
304
+ // --- one scenario's run -----------------------------------------------------
305
+
306
+ interface Lane {
307
+ context: BrowserContext;
308
+ active: Page;
309
+ opened: Page[];
310
+ net: ResponseLog;
311
+ /** The latest response the session's request client got (see Run.send). */
312
+ last?: Exchange;
313
+ }
314
+
315
+ /** One API request and its response. */
316
+ interface Exchange {
317
+ method: string;
318
+ url: string;
319
+ status: number;
320
+ headers: Record<string, string>;
321
+ body?: string;
322
+ durationMs: number;
323
+ }
324
+
325
+ /** A request as the spec writes it: every text resolved, a typed leaf already a number or a boolean. */
326
+ export interface RequestSpec {
327
+ method: string;
328
+ /** Relative to the API's base URL; a full URL goes to another host. */
329
+ path: string;
330
+ /** The API it goes to, by its name in api.services; absent, the default API. */
331
+ service?: string;
332
+ headers?: Record<string, string>;
333
+ body?: unknown;
334
+ form?: Record<string, string>;
335
+ multipart?: Record<string, string | { $file: string }>;
336
+ /** Sent again until the response has the expected status and satisfies these checks. */
337
+ until?: { json?: ResponseJsonCheck[]; intervalMs?: number; timeoutMs?: number };
338
+ idempotent?: boolean;
339
+ timeoutMs?: number;
340
+ /** The expected status ("201" or "2xx"; default any 2xx). */
341
+ status?: string;
342
+ /** Response fields to keep for {captured:name}: name to JSON Pointer, or header:Name. */
343
+ extract?: Record<string, string>;
344
+ /** The request carries an {env:...} value: it is sent to its API's base URL and nowhere else. */
345
+ secret?: boolean;
346
+ }
347
+
348
+ const IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
349
+
350
+ /**
351
+ * Whether a URL's host is a link-local address: 169.254.0.0/16, fe80::/10,
352
+ * or either mapped into IPv6; or AWS's IPv6 metadata address, fd00:ec2::254,
353
+ * which serves the same credentials. Read as written.
354
+ */
355
+ function isLinkLocal(hostname: string): boolean {
356
+ const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
357
+ if (/^169\.254\.\d{1,3}\.\d{1,3}$/.test(host)) return true;
358
+ if (/^fe[89ab][0-9a-f]?:/.test(host) || host === "fd00:ec2::254") return true;
359
+ const mapped = /^::ffff:(?:(\d{1,3}(?:\.\d{1,3}){3})|([0-9a-f]{1,4}):[0-9a-f]{1,4})$/.exec(host);
360
+ if (mapped) return mapped[1] ? /^169\.254\./.test(mapped[1]) : parseInt(mapped[2], 16) === 0xa9fe;
361
+ return false;
362
+ }
363
+
364
+ /** A file's media type from its extension, for a multipart part; octet-stream when unknown. */
365
+ function mimeTypeOf(file: string): string {
366
+ const types: Record<string, string> = { ".json": "application/json", ".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml", ".txt": "text/plain", ".csv": "text/csv", ".xml": "application/xml", ".html": "text/html", ".zip": "application/zip" };
367
+ return types[path.extname(file).toLowerCase()] ?? "application/octet-stream";
368
+ }
369
+
370
+ /** A schema the contract gives, whole, in the JSON Schema dialect of its contract (OpenAPI 3.1: 2020-12; 3.0: draft-07). */
371
+ export interface ExportedSchema {
372
+ dialect: "2020-12" | "draft-07";
373
+ schema: unknown;
374
+ }
375
+
376
+ /** A schema check as the spec holds it: one named schema, or an operation's by response key ("201", "4XX", "default"). */
377
+ export interface SchemaCheck {
378
+ what: string;
379
+ schema?: ExportedSchema;
380
+ responses?: Record<string, ExportedSchema | "no-body" | "no-schema">;
381
+ }
382
+
383
+ type Validator = ((value: unknown) => boolean) & { errors?: { instancePath: string; message?: string; params?: Record<string, unknown> }[] | null };
384
+
385
+ const compiled = new Map<string, Validator>();
386
+
387
+ /**
388
+ * A schema compiled with ajv and ajv-formats, as replay compiles the pinned
389
+ * contract: formats checked, no strict mode, all errors. Loaded only by a
390
+ * schema check, so a suite with none needs neither installed.
391
+ */
392
+ async function compiledSchema(target: ExportedSchema): Promise<Validator> {
393
+ const key = JSON.stringify(target);
394
+ const known = compiled.get(key);
395
+ if (known) return known;
396
+ // By name, so a project without ajv type-checks and runs every other check.
397
+ const load = (name: string) => import(name);
398
+ let Engine: new (options: object) => { compile(schema: unknown): Validator };
399
+ let addFormats: (ajv: unknown) => void;
400
+ try {
401
+ const core = target.dialect === "2020-12" ? await load("ajv/dist/2020.js") : await load("ajv");
402
+ Engine = target.dialect === "2020-12" ? (core.Ajv2020 ?? core.default?.Ajv2020 ?? core.default) : (core.Ajv ?? core.default?.Ajv ?? core.default);
403
+ const formats = await load("ajv-formats");
404
+ addFormats = formats.default?.default ?? formats.default ?? formats;
405
+ } catch {
406
+ throw new Error("the schema check needs ajv and ajv-formats: npm install --save-dev ajv@^8 ajv-formats@^3");
407
+ }
408
+ const ajv = new Engine({ strict: false, allErrors: true, validateFormats: true, allowUnionTypes: true, logger: false });
409
+ addFormats(ajv);
410
+ const validate = ajv.compile(target.schema);
411
+ compiled.set(key, validate);
412
+ return validate;
413
+ }
414
+
415
+ /** The start of a response body, for an error line. */
416
+ function excerpt(body: string | undefined): string {
417
+ if (!body) return "";
418
+ const line = mask(body).replace(/\s+/g, " ").trim();
419
+ return line ? `: ${line.length > 300 ? `${line.slice(0, 300)}...` : line}` : "";
420
+ }
421
+
422
+ /** A response header by name, whatever its case. */
423
+ const headerOf = (headers: Record<string, string>, name: string) => Object.entries(headers).find(([k]) => k.toLowerCase() === name.toLowerCase())?.[1];
424
+
425
+ /**
426
+ * One scenario: its browser sessions (each a context with its own tabs and
427
+ * network log), the values it captured, its {unique...} seed and its clock.
428
+ */
429
+ export class Run {
430
+ private lanes = new Map<string, Lane>();
431
+ private lane!: Lane;
432
+ private vars = new Map<string, string>();
433
+ /** The credentials this scenario's requests captured: sent only to the APIs under test, as replay keeps them per execution. */
434
+ private credentials = new Map<string, string>();
435
+ private seed = `${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
436
+ /** One clock per scenario: a day picked in one step is the day a later step checks. */
437
+ readonly now = new Date();
438
+ private download?: string;
439
+ /** The dialog answer armed on each page and not used yet. */
440
+ private dialogs = new WeakMap<Page, (dialog: Dialog) => void>();
441
+ /** What capture() read, and from which element, for expectDiffers. */
442
+ private captures = new Map<string, ElementHandle>();
443
+
444
+ private constructor(private browser: Browser, private baseURL: string | undefined) {}
445
+
446
+ static async start({ page, browser, baseURL }: { page: Page; browser: Browser; baseURL?: string }): Promise<Run> {
447
+ const run = new Run(browser, baseURL);
448
+ run.lane = run.track(page.context(), page);
449
+ run.lanes.set("", run.lane);
450
+ return run;
451
+ }
452
+
453
+ private track(context: BrowserContext, active: Page): Lane {
454
+ const lane: Lane = { context, active, opened: [], net: new ResponseLog(context) };
455
+ context.on("page", (p) => lane.opened.push(p));
456
+ return lane;
457
+ }
458
+
459
+ /** The tab the scenario acts on: a tab an action opened is followed, as replay follows it. */
460
+ get page(): Page {
461
+ const lane = this.lane;
462
+ while (lane.opened.length > 0) {
463
+ const fresh = lane.opened.shift()!;
464
+ if (!fresh.isClosed()) lane.active = fresh;
465
+ }
466
+ return lane.active;
467
+ }
468
+
469
+ /** Act as another browser session (`As "buyer"`): a context of its own. */
470
+ async use(session = ""): Promise<void> {
471
+ let lane = this.lanes.get(session);
472
+ if (!lane) {
473
+ // Signed in as the project is unless the session has its own state, as in replay.
474
+ const storageState = SETTINGS.sessions[session]?.storageState ?? SETTINGS.storageState;
475
+ const use = test.info().project.use;
476
+ const context = await this.browser.newContext({
477
+ viewport: use.viewport,
478
+ locale: use.locale,
479
+ timezoneId: use.timezoneId,
480
+ userAgent: use.userAgent,
481
+ deviceScaleFactor: use.deviceScaleFactor,
482
+ isMobile: use.isMobile,
483
+ hasTouch: use.hasTouch,
484
+ baseURL: this.baseURL,
485
+ ...(storageState ? { storageState: projectFile(storageState) } : {}),
486
+ });
487
+ lane = this.track(context, await context.newPage());
488
+ this.lanes.set(session, lane);
489
+ }
490
+ this.lane = lane;
491
+ }
492
+
493
+ async close(): Promise<void> {
494
+ for (const [session, lane] of this.lanes) if (session !== "") await lane.context.close();
495
+ }
496
+
497
+ /** A recorded URL under the base URL, as Saffron joins them (a base path is kept). */
498
+ url(recorded: string): string {
499
+ return this.join(recorded, this.baseURL, `relative navigation "${recorded}" needs a baseURL in playwright.config.ts`);
500
+ }
501
+
502
+ private join(recorded: string, baseURL: string | undefined, orElse: string): string {
503
+ if (/^[a-z][a-z\d+.-]*:|^\/\//i.test(recorded)) return recorded;
504
+ if (!baseURL) throw new Error(orElse);
505
+ const base = new URL(baseURL);
506
+ const prefix = base.pathname.replace(/\/+$/, "");
507
+ const hashAt = recorded.indexOf("#");
508
+ const hash = hashAt >= 0 ? recorded.slice(hashAt) : undefined;
509
+ const beforeHash = hashAt >= 0 ? recorded.slice(0, hashAt) : recorded;
510
+ const queryAt = beforeHash.indexOf("?");
511
+ const query = queryAt >= 0 ? beforeHash.slice(queryAt) : undefined;
512
+ const pathPart = queryAt >= 0 ? beforeHash.slice(0, queryAt) : beforeHash;
513
+ const isBase = pathPart === "" || pathPart === "/";
514
+ const out = new URL(base.href);
515
+ out.pathname = isBase ? base.pathname : `${prefix}${pathPart.startsWith("/") ? pathPart : `/${pathPart}`}`;
516
+ out.search = query === undefined ? base.search : query === "?" ? "" : query;
517
+ out.hash = hash === "#" ? "" : hash !== undefined ? hash : isBase ? base.hash : "";
518
+ return out.toString();
519
+ }
520
+
521
+ /** A {unique:name} or {unique:name:digits} value: new each run, the same within one. */
522
+ unique(token: string): string {
523
+ const [, name, digits] = /^\{unique:([A-Za-z0-9_-]+)(?::(digits))?\}$/.exec(token)!;
524
+ const hash = createHash("sha1").update(`${this.seed}:${name}`).digest();
525
+ if (digits) return String(100_000_000 + ((hash.readUInt32BE(0) * 2 ** 16 + hash.readUInt16BE(4)) % 900_000_000));
526
+ const body = BigInt(`0x${hash.subarray(0, 8).toString("hex")}`).toString(36).padStart(9, "0").slice(-9);
527
+ return `${"abcdefghijklmnopqrstuvwxyz"[hash[8] % 26]}${body}`;
528
+ }
529
+
530
+ /** A {date...} token on this scenario's clock. */
531
+ date(token: string): string {
532
+ return date(token, this.now);
533
+ }
534
+
535
+ /** A Gherkin step starts: network waits look from the previous step on, in every session. */
536
+ step(): void {
537
+ for (const lane of this.lanes.values()) lane.net.markStep();
538
+ }
539
+
540
+ /** Answer the next native dialog on the active tab; a newer answer replaces one no dialog used. */
541
+ dialog(accept: boolean, promptText?: string): void {
542
+ const page = this.page;
543
+ const unused = this.dialogs.get(page);
544
+ if (unused) page.off("dialog", unused);
545
+ const answer = (dialog: Dialog) => {
546
+ this.dialogs.delete(page);
547
+ void (accept ? dialog.accept(promptText) : dialog.dismiss()).catch(() => undefined);
548
+ };
549
+ this.dialogs.set(page, answer);
550
+ page.once("dialog", answer);
551
+ }
552
+
553
+ /** A browser action is about to run: network checks count from here. */
554
+ act(): void {
555
+ this.lane.net.markAction();
556
+ }
557
+
558
+ /**
559
+ * After an action in a scenario that uses tabs: a tab it opened becomes
560
+ * the one the scenario acts on, unless a modified or middle click opened
561
+ * it in the background. `opens` says the recording saw one open, and then
562
+ * one must.
563
+ */
564
+ async tabs(opens = false, background = false): Promise<void> {
565
+ const lane = this.lane;
566
+ if (background) {
567
+ // Opened behind the page clicked: noted, not followed.
568
+ await lane.context.waitForEvent("page", { timeout: 150 }).catch(() => undefined);
569
+ lane.opened.length = 0;
570
+ return;
571
+ }
572
+ if (lane.opened.length === 0) {
573
+ await lane.context.waitForEvent("page", { timeout: opens ? SETTINGS.timeoutMs : 150 }).catch(() => undefined);
574
+ }
575
+ if (opens && lane.opened.length === 0) throw new Error("this action opened a new tab when it was recorded, and none opened now");
576
+ while (lane.opened.length > 0) {
577
+ const fresh = lane.opened.shift()!;
578
+ await fresh.waitForLoadState("domcontentloaded").catch(() => undefined);
579
+ if (!background) lane.active = fresh;
580
+ }
581
+ }
582
+
583
+ private openPages = () => this.lane.context.pages().filter((p) => !p.isClosed());
584
+
585
+ /** Act on tab `index` (0-based, in the order they opened). */
586
+ async switchTab(index: number): Promise<void> {
587
+ await expect.poll(() => this.openPages().length > index, { message: `tab ${index} to exist`, timeout: SETTINGS.timeoutMs }).toBe(true);
588
+ const target = this.openPages()[index];
589
+ await target.bringToFront();
590
+ this.lane.active = target;
591
+ }
592
+
593
+ async newTab(url?: string): Promise<void> {
594
+ this.act();
595
+ const fresh = await this.lane.context.newPage();
596
+ this.lane.opened.length = 0;
597
+ if (url !== undefined) await fresh.goto(this.url(url));
598
+ this.lane.active = fresh;
599
+ }
600
+
601
+ /** Close tab `index`, or the active one; the newest tab left becomes active. */
602
+ async closeTab(index?: number): Promise<void> {
603
+ this.act();
604
+ const target = index === undefined ? this.lane.active : this.openPages()[index];
605
+ if (!target) throw new Error(`tab ${index} does not exist`);
606
+ await target.close();
607
+ const remaining = this.openPages();
608
+ if (remaining.length === 0) throw new Error("closed the last tab; nothing left to drive");
609
+ this.lane.active = remaining[remaining.length - 1];
610
+ }
611
+
612
+ /** Run `action`, which must start `count` downloads; the latest is the one expectDownload reads. */
613
+ async downloads(count: number, action: () => Promise<unknown>): Promise<void> {
614
+ const started: Download[] = [];
615
+ const onDownload = (d: Download) => void started.push(d);
616
+ const hear = (p: Page) => void p.on("download", onDownload);
617
+ const context = this.lane.context;
618
+ context.pages().forEach(hear);
619
+ context.on("page", hear);
620
+ try {
621
+ await action().catch((err) => {
622
+ if (!/Download is starting/.test(String(err))) throw err;
623
+ });
624
+ await expect.poll(() => started.length, { message: `${count} download(s) to start`, timeout: SETTINGS.timeoutMs }).toBeGreaterThanOrEqual(count);
625
+ const latest = started[started.length - 1];
626
+ const failure = await latest.failure();
627
+ if (failure) throw new Error(`the download of ${latest.suggestedFilename()} failed (${failure})`);
628
+ const file = path.join(test.info().outputPath("downloads"), path.basename(latest.suggestedFilename()) || "download");
629
+ await latest.saveAs(file);
630
+ this.download = file;
631
+ } finally {
632
+ context.off("page", hear);
633
+ for (const p of context.pages()) p.off("download", onDownload);
634
+ }
635
+ }
636
+
637
+ /** Run `action`, which must open a file chooser, and give it `files`. */
638
+ async chooseFiles(files: string[], action: () => Promise<unknown>): Promise<void> {
639
+ const chooser = this.page.waitForEvent("filechooser", { timeout: SETTINGS.timeoutMs });
640
+ chooser.catch(() => undefined); // the action's own error comes first
641
+ await action();
642
+ await (await chooser).setFiles(files.map(projectFile));
643
+ }
644
+
645
+ /** The text `target` shows, once open requests are answered and the text has held for half a second. */
646
+ async capture(name: string, target: Locator): Promise<void> {
647
+ await this.lane.net.quiet(Math.min(SETTINGS.timeoutMs / 2, 3000));
648
+ const settle = Math.min(500, SETTINGS.timeoutMs / 4);
649
+ const deadline = Date.now() + SETTINGS.timeoutMs - settle;
650
+ let seen: { text: string; since: number } | undefined;
651
+ await expect
652
+ .poll(
653
+ async () => {
654
+ const text = await shown(target);
655
+ if (!text) return false;
656
+ const at = Date.now();
657
+ if (seen?.text !== text) seen = { text, since: at };
658
+ if (at - seen.since < settle && at < deadline) return false;
659
+ const element = await target.first().elementHandle({ timeout: 1000 }).catch(() => null);
660
+ if (!element) return false;
661
+ await this.captures.get(name)?.dispose().catch(() => undefined);
662
+ this.captures.set(name, element);
663
+ this.vars.set(name, text);
664
+ return true;
665
+ },
666
+ { message: `non-empty text to capture as "${name}"`, timeout: SETTINGS.timeoutMs },
667
+ )
668
+ .toBe(true);
669
+ }
670
+
671
+ captured(name: string): string {
672
+ const value = this.vars.get(name);
673
+ if (value === undefined) throw new Error(`no captured value named "${name}"`);
674
+ return value;
675
+ }
676
+
677
+ /**
678
+ * The target's text differs from what `compareTo` captured (no target: two
679
+ * captures differ). The element compared is the one captured when the
680
+ * capture read this same target (`same`), else the first found: never
681
+ * whichever element happens to be first at each look.
682
+ */
683
+ async expectDiffers(compareTo: string, target?: Locator, left?: string, same = false): Promise<void> {
684
+ const right = this.captured(compareTo);
685
+ if (!target) {
686
+ expect(this.captured(left ?? ""), `"${left}" to differ from "${compareTo}"`).not.toBe(right);
687
+ return;
688
+ }
689
+ let element: ElementHandle | undefined = same ? this.captures.get(compareTo) : undefined;
690
+ await expect
691
+ .poll(async () => {
692
+ element ??= (await target.first().elementHandle({ timeout: 1000 }).catch(() => null)) ?? undefined;
693
+ if (!element) return false;
694
+ const text = await drawn(element);
695
+ if (text === "" || text === right) return false;
696
+ // The element must still be one the target names.
697
+ return target.evaluateAll((els, el) => els.includes(el as Element), element).catch(() => false);
698
+ }, { message: `target text to differ from "${compareTo}" (${right})`, timeout: SETTINGS.timeoutMs })
699
+ .toBe(true);
700
+ }
701
+
702
+ /** A response matching the recorded request has been seen (a wait) or was answered since the latest action (a check). */
703
+ async response(kind: "wait" | "check", match: { url: string; method?: string; status?: string; body?: string; json?: ResponseJsonCheck[] }): Promise<void> {
704
+ if (match.url === "" || match.method === "" || match.status === "" || match.body === "") throw new Error("a response check with a blank part would match any response");
705
+ const url = pattern(match.url);
706
+ const body = match.body !== undefined ? pattern(match.body) : undefined;
707
+ if (match.json) {
708
+ const malformed = responseJsonProblem(match.json);
709
+ if (malformed) throw new Error(`Response json ${malformed}`);
710
+ jsonChecksReadable(match.json);
711
+ }
712
+ const net = this.lane.net;
713
+ await expect
714
+ .poll(
715
+ () =>
716
+ (kind === "check" ? net.sinceAction() : net.sincePreviousStep()).some(
717
+ (e) =>
718
+ (url.test(e.url) || url.test(decode(e.url))) &&
719
+ (!match.method || e.method.toUpperCase() === match.method.toUpperCase()) &&
720
+ statusMatches(e.status, match.status) &&
721
+ (!match.json || checkResponseJson(e.body, match.json) === undefined) &&
722
+ (!body || (e.body !== undefined && body.test(e.body))),
723
+ ),
724
+ { message: `a ${match.method ?? ""} response from /${match.url}/ with status ${match.status ?? "2xx"}${match.body ? ` and a body matching /${match.body}/` : ""}${match.json ? ` whose JSON fields pass ${match.json.length} check(s)` : ""}`, timeout: SETTINGS.timeoutMs },
725
+ )
726
+ .toBe(true);
727
+ }
728
+
729
+ /**
730
+ * The base URL of an API: API_URL (the default API) or API_URL_<NAME> (a
731
+ * named one, its name upper-cased, other characters as _) from the
732
+ * environment, else api.baseURL or api.services.<name>.baseURL from
733
+ * saffron.config.json; the default API falls back to the test's baseURL.
734
+ */
735
+ apiBase(service?: string): string | undefined {
736
+ if (service === undefined) return process.env.API_URL || SETTINGS.api.baseURL || this.baseURL;
737
+ const configured = SETTINGS.api.services[service];
738
+ if (configured === undefined) throw new Error(`no API service named "${service}": api.services in saffron.config.json has ${Object.keys(SETTINGS.api.services).map((n) => `"${n}"`).join(", ") || "none"}`);
739
+ return process.env[`API_URL_${service.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`] || configured;
740
+ }
741
+
742
+ /**
743
+ * Send a request through the active session's request client, so a call
744
+ * after a UI sign-in carries its cookies, and keep its response for the
745
+ * checks that follow. The response must have the expected status; a
746
+ * polled request (`until`) is sent again until it does and its checks
747
+ * hold, and only a GET, HEAD, OPTIONS or idempotent request polls.
748
+ */
749
+ async send(spec: RequestSpec): Promise<void> {
750
+ const method = spec.method.toUpperCase();
751
+ const where = spec.service === undefined ? "api.baseURL" : `api.services.${spec.service}.baseURL`;
752
+ if (spec.until !== undefined && !(spec.idempotent ?? IDEMPOTENT_METHODS.has(method))) {
753
+ throw new Error(`${method} ${spec.path} polls (until), and a ${method} may not be sent twice: poll with a GET that reads the state, or mark the request idempotent`);
754
+ }
755
+ const base = this.apiBase(spec.service);
756
+ const url = this.join(spec.path, base, `${method} ${mask(spec.path)} is relative, and no API base URL is set: set ${where} in saffron.config.json, API_URL in the environment, or baseURL in playwright.config.ts`);
757
+ if (isLinkLocal(new URL(url).hostname) || (await resolvesLinkLocal(new URL(url).hostname))) throw new Error(`${method} ${mask(url)} goes to a link-local address, where a cloud keeps its metadata and credentials, so it is never sent.`);
758
+ // A credential the API handed out goes to the APIs under test and nowhere else.
759
+ const sent = JSON.stringify([url, spec.headers, spec.body, spec.form, spec.multipart]);
760
+ const credential = [...this.credentials].find(([, value]) => value.length >= 3 && (sent.includes(value) || sent.includes(JSON.stringify(value).slice(1, -1))))?.[0];
761
+ const origins = new Set([undefined, ...Object.keys(SETTINGS.api.services)].flatMap((name) => {
762
+ const api = this.apiBase(name);
763
+ return api ? [new URL(api).origin] : [];
764
+ }));
765
+ if (credential !== undefined) {
766
+ if (!origins.has(new URL(url).origin)) throw new Error(`${method} ${mask(url)} carries {captured:${credential}}, a credential the API handed out, to ${new URL(url).origin}, which is not an API under test: a captured credential is only sent to one.`);
767
+ }
768
+ // A secret goes to the API under test and nowhere else.
769
+ if (spec.secret && new URL(url).origin !== (base ? new URL(base).origin : undefined)) {
770
+ throw new Error(`${method} ${mask(url)} carries an {env:...} value to ${new URL(url).origin}, which is not the API's base URL${base ? ` (${new URL(base).origin})` : ""}: a request with an {env:...} value is only sent there. Set ${where} to the API that should receive it.`);
771
+ }
772
+ let multipart: Record<string, string | { name: string; mimeType: string; buffer: Buffer }> | undefined;
773
+ if (spec.multipart !== undefined) {
774
+ multipart = {};
775
+ for (const [field, part] of Object.entries(spec.multipart)) {
776
+ if (typeof part === "string") {
777
+ multipart[field] = part;
778
+ continue;
779
+ }
780
+ const root = path.resolve(path.dirname(test.info().file), SETTINGS.projectRoot);
781
+ const file = path.resolve(root, part.$file);
782
+ if (file !== root && !file.startsWith(root + path.sep)) throw new Error(`${part.$file} is outside the project: a request sends only the project's own files`);
783
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new Error(`${part.$file} is not a file of the project, so the request cannot send it`);
784
+ // A link inside the project that leads out of it is outside too.
785
+ if (!fs.realpathSync(file).startsWith(fs.realpathSync(root) + path.sep)) throw new Error(`${part.$file} is outside the project: a request sends only the project's own files`);
786
+ // A hidden file or folder (.env, .git, .npmrc) holds the project's secrets and settings, as replay reads it.
787
+ const hidden = (rel: string) => rel.split(path.sep).some((piece) => piece.startsWith("."));
788
+ if (hidden(path.relative(root, file)) || hidden(path.relative(fs.realpathSync(root), fs.realpathSync(file)))) throw new Error(`${part.$file} is a hidden file of the project (.env, .git and the like hold its secrets), so a request never sends it`);
789
+ // A hard link is the same file under a second name, which no path tells: it may be .env.
790
+ if (fs.statSync(file).nlink > 1) throw new Error(`${part.$file} is a hard link (the same file under another name, perhaps a hidden one such as .env), so a request never sends it: copy the file instead`);
791
+ // A file of the project goes to the APIs under test and nowhere else.
792
+ if (!origins.has(new URL(url).origin)) throw new Error(`${method} ${mask(url)} sends a file of the project to ${new URL(url).origin}, which is not an API under test: a request sends the project's files only to one.`);
793
+ multipart[field] = { name: path.basename(file), mimeType: mimeTypeOf(file), buffer: fs.readFileSync(file) };
794
+ }
795
+ }
796
+ const until = spec.until === undefined ? undefined : { checks: spec.until.json ?? [], intervalMs: spec.until.intervalMs ?? 1000, deadline: Date.now() + (spec.until.timeoutMs ?? 30_000) };
797
+ // A poll is a wait for a state, as replay bounds it: every 100 ms at the fastest, 10 minutes at the longest.
798
+ if (until && until.intervalMs < 100) throw new Error(`${method} ${spec.path} polls every ${until.intervalMs} ms, faster than the 100 ms a poll may`);
799
+ if (until && (spec.until!.timeoutMs ?? 30_000) > 600_000) throw new Error(`${method} ${spec.path} polls for ${spec.until!.timeoutMs} ms, longer than the 10 minutes a poll may wait`);
800
+ if (until) jsonChecksReadable(until.checks);
801
+ const lane = this.lane;
802
+ const attempt = async (): Promise<Exchange> => {
803
+ const started = Date.now();
804
+ let response: APIResponse;
805
+ try {
806
+ response = await lane.context.request.fetch(url, {
807
+ method,
808
+ headers: spec.headers,
809
+ ...(spec.body === undefined ? {} : { data: spec.body as string | object }),
810
+ ...(spec.form === undefined ? {} : { form: spec.form }),
811
+ ...(multipart === undefined ? {} : { multipart }),
812
+ timeout: spec.timeoutMs ?? SETTINGS.timeoutMs,
813
+ failOnStatusCode: false,
814
+ maxRedirects: 0,
815
+ });
816
+ } catch (err) {
817
+ // Playwright's message ends in a call log listing the request's headers: only its first line is kept.
818
+ const reason = (err instanceof Error ? err.message : String(err)).split("\n")[0].replace(/^apiRequestContext\.fetch:\s*/, "").trim();
819
+ throw new Error(mask(`${method} ${url} got no response: ${reason}`));
820
+ }
821
+ const body = await response.text().catch(() => undefined);
822
+ return (lane.last = { method, url, status: response.status(), headers: response.headers(), body, durationMs: Date.now() - started });
823
+ };
824
+ const notYet = (exchange: Exchange): string | undefined => {
825
+ if (!statusMatches(exchange.status, spec.status)) return `returned ${exchange.status}, expected ${spec.status ?? "2xx"}${excerpt(exchange.body)}`;
826
+ const problem = until && until.checks.length > 0 ? checkResponseJson(exchange.body, until.checks) : undefined;
827
+ return problem ? `${problem}${excerpt(exchange.body)}` : undefined;
828
+ };
829
+ let exchange = await attempt();
830
+ while (until !== undefined && notYet(exchange) !== undefined && Date.now() + until.intervalMs <= until.deadline) {
831
+ await new Promise<void>((r) => setTimeout(r, until.intervalMs));
832
+ exchange = await attempt();
833
+ }
834
+ // A response the step fails on still hands out its credentials, and the error quotes its body: they are known first.
835
+ for (const [name, pointer] of Object.entries(spec.extract ?? {})) {
836
+ if (!isCredentialCapture(name, pointer)) continue;
837
+ const header = /^header:(.+)$/i.exec(pointer);
838
+ let value: unknown;
839
+ try {
840
+ value = header ? headerOf(exchange.headers, header[1]) : at(JSON.parse(exchange.body ?? ""), pointer);
841
+ } catch {
842
+ value = undefined;
843
+ }
844
+ if (value !== undefined) {
845
+ const kept = typeof value === "string" ? value : JSON.stringify(value);
846
+ this.credentials.set(name, kept);
847
+ CREDENTIALS.set(name, kept);
848
+ }
849
+ }
850
+ const problem = notYet(exchange);
851
+ if (problem !== undefined) throw new Error(mask(until === undefined ? `${method} ${url} ${problem}` : `${method} ${url} still ${problem} after ${spec.until!.timeoutMs ?? 30_000} ms of polling`));
852
+ for (const [name, pointer] of Object.entries(spec.extract ?? {})) {
853
+ const header = /^header:(.+)$/i.exec(pointer);
854
+ if (header) {
855
+ const value = headerOf(exchange.headers, header[1]);
856
+ if (value === undefined) throw new Error(mask(`${method} ${url}: the response has no ${header[1]} header to extract as "${name}"`));
857
+ this.vars.set(name, value);
858
+ continue;
859
+ }
860
+ let parsed: unknown;
861
+ try {
862
+ parsed = JSON.parse(exchange.body ?? "");
863
+ } catch {
864
+ throw new Error(mask(`${method} ${url} returned no JSON body, so "${name}" (${pointer || "/"}) cannot be extracted${excerpt(exchange.body)}`));
865
+ }
866
+ const value = at(parsed, pointer);
867
+ if (value === undefined) throw new Error(mask(`${method} ${url}: the response has no ${pointer || "/"} to extract as "${name}"${excerpt(exchange.body)}`));
868
+ this.vars.set(name, typeof value === "string" ? value : JSON.stringify(value));
869
+ }
870
+ }
871
+
872
+ private latest(): Exchange {
873
+ if (!this.lane.last) throw new Error("no request was sent yet in this step's session: a response check needs a request before it");
874
+ return this.lane.last;
875
+ }
876
+
877
+ /** The latest response's status is `expected`: a code ("404") or a class ("2xx"). */
878
+ expectStatus(expected: string): void {
879
+ const last = this.latest();
880
+ if (expected.trim() === "") throw new Error("an expected status is blank, so it would hold for anything");
881
+ if (!statusMatches(last.status, expected)) throw new Error(mask(`expected the response status ${expected}, but ${last.method} ${last.url} returned ${last.status}${excerpt(last.body)}`));
882
+ }
883
+
884
+ /** The latest response's JSON fields pass every check, as replay checks them. */
885
+ expectJson(checks: ResponseJsonCheck[]): void {
886
+ const last = this.latest();
887
+ const malformed = responseJsonProblem(checks);
888
+ if (malformed) throw new Error(`Response json ${malformed}`);
889
+ jsonChecksReadable(checks);
890
+ const problem = checkResponseJson(last.body, checks);
891
+ if (problem) throw new Error(mask(`${last.method} ${last.url}: ${problem}`));
892
+ }
893
+
894
+ /** The latest response has the header: equal to `value`, matching `pattern`, or present when neither is given. */
895
+ expectHeader(name: string, expected: { value?: string; pattern?: string } = {}): void {
896
+ const last = this.latest();
897
+ const value = headerOf(last.headers, name);
898
+ const where = `${last.method} ${last.url}`;
899
+ if (value === undefined) throw new Error(mask(`${where}: the response has no ${name} header${Object.keys(last.headers).length > 0 ? ` (it has ${Object.keys(last.headers).join(", ")})` : ""}`));
900
+ if (expected.value !== undefined) {
901
+ if (value !== expected.value) throw new Error(mask(`${where}: expected the ${name} header to be ${JSON.stringify(expected.value)}, got ${JSON.stringify(value)}`));
902
+ } else if (expected.pattern !== undefined) {
903
+ let re: RegExp;
904
+ try {
905
+ re = new RegExp(expected.pattern);
906
+ } catch {
907
+ throw new Error(`expectHeader: /${expected.pattern}/ is not a regular expression`);
908
+ }
909
+ if (!re.test(value)) throw new Error(mask(`${where}: expected the ${name} header to match /${expected.pattern}/, got ${JSON.stringify(value)}`));
910
+ }
911
+ }
912
+
913
+ /**
914
+ * The latest response's body matches the pinned contract, as replay
915
+ * checks it: the one schema the check names, or the schema the operation
916
+ * gives the response's status (its code, its class, or the default), and
917
+ * no body where the contract gives the response none. The schemas were
918
+ * resolved from the contract when the spec was written (SCHEMAS).
919
+ */
920
+ async expectSchema(check: SchemaCheck): Promise<void> {
921
+ const last = this.latest();
922
+ let target = check.schema;
923
+ if (!target) {
924
+ const n = Math.floor(last.status / 100);
925
+ const key = [String(last.status), `${n}XX`, `${n}xx`, "default"].find((k) => check.responses?.[k] !== undefined);
926
+ const entry = key === undefined ? "no-schema" : check.responses![key];
927
+ if (entry === "no-body") {
928
+ if ((last.body ?? "").trim() === "") return;
929
+ throw new Error(mask(`${check.what} give a ${last.status} response no body, and ${last.method} ${last.url} returned one${excerpt(last.body)}`));
930
+ }
931
+ if (entry === "no-schema") throw new Error(`${check.what} give no JSON schema for a ${last.status} response`);
932
+ target = entry;
933
+ }
934
+ let value: unknown;
935
+ try {
936
+ value = JSON.parse(last.body ?? "");
937
+ } catch {
938
+ throw new Error(mask(`${last.method} ${last.url} returned no JSON body to check against ${check.what}${excerpt(last.body)}`));
939
+ }
940
+ const validate = await compiledSchema(target);
941
+ if (validate(value)) return;
942
+ const errors = (validate.errors ?? []).slice(0, 5).map((e) => `${e.instancePath || "/"} ${e.message ?? "is invalid"}${e.params && "additionalProperty" in e.params ? ` (${String(e.params.additionalProperty)})` : ""}`);
943
+ throw new Error(mask(`the ${last.method} ${last.url} response does not match ${check.what}: ${errors.join("; ")}`));
944
+ }
945
+
946
+ /** The latest response arrived within `maxMs` milliseconds, from sending the request to its body being read. */
947
+ expectDuration(maxMs: number): void {
948
+ const last = this.latest();
949
+ if (last.durationMs > maxMs) throw new Error(mask(`${last.method} ${last.url} took ${last.durationMs} ms, more than the ${maxMs} ms the step allows`));
950
+ }
951
+
952
+ /** The latest download, read as text, contains `value` and matches `source` (case-sensitive, ^ and $ at each line). */
953
+ async expectDownload(value?: string | RegExp, source?: string): Promise<void> {
954
+ if (!this.download) throw new Error("expectDownload: no file was downloaded in this scenario before this check");
955
+ const name = path.basename(this.download);
956
+ const { size } = await fs.promises.stat(this.download);
957
+ if (size > 5 * 1024 * 1024) throw new Error(`the downloaded file ${name} is ${size} bytes; a content check reads text files up to 5 MB`);
958
+ const bytes = await fs.promises.readFile(this.download);
959
+ if (bytes.includes(0)) throw new Error(`the downloaded file ${name} is not a UTF-8 text file`);
960
+ let text = new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^/, "").replace(/\r\n?/g, "\n");
961
+ if (/\.(ics|ical|ifb|vcf|vcs)$/i.test(name)) text = text.replace(/\n[ \t]/g, "");
962
+ if (value !== undefined) expect(contains(text, said(value, "the text the downloaded file must contain")), `the downloaded file ${name} to contain ${value}`).toBe(true);
963
+ if (source !== undefined) expect(text).toMatch(pattern(source, "m"));
964
+ }
965
+ }
966
+
967
+ // --- checks on elements ---------------------------------------------------
968
+
969
+ /** The text the target's first match shows, whitespace collapsed; "" when it is not visible. */
970
+ async function shown(target: Locator): Promise<string> {
971
+ try {
972
+ const element = await target.first().elementHandle({ timeout: 1000 });
973
+ return element ? normalize((await read(element)).text) : "";
974
+ } catch {
975
+ return "";
976
+ }
977
+ }
978
+
979
+ const drawn = async (element: ElementHandle) => normalize((await read(element).catch(() => ({ text: "" }))).text);
980
+
981
+ /**
982
+ * Saffron's own reading of the text an element draws, the one replay
983
+ * checks: text nodes joined as the page holds them (not innerText, which
984
+ * adds line breaks between blocks and applies text-transform), and each
985
+ * drawn line on its own. Written in by saffron eject.
986
+ */
987
+ const DRAWN_TEXT: string = /*DRAWN_TEXT*/ "" /*END*/;
988
+
989
+ /** The element's drawn text and its lines; nothing when it draws none. */
990
+ async function read(element: ElementHandle): Promise<{ text: string; pieces: string[] }> {
991
+ return element.evaluate((el, src) => (0, eval)(`(${src})`)(el, true), DRAWN_TEXT);
992
+ }
993
+
994
+ /** The lines an element shows, as replay's expectEach reads them. */
995
+ async function lines(element: ElementHandle): Promise<string[]> {
996
+ return (await read(element)).pieces;
997
+ }
998
+
999
+ const poll = (check: () => Promise<boolean>, message: string) =>
1000
+ expect.poll(check, { message, timeout: SETTINGS.timeoutMs }).toBe(true);
1001
+
1002
+ /** The target shows `text` (a string is a plain substring; see bounded). */
1003
+ export async function expectText(target: Locator, text: string | RegExp): Promise<void> {
1004
+ const needle = said(typeof text === "string" ? normalize(text) : text, "the expected text");
1005
+ await poll(async () => contains(await shown(target), needle), `target text to contain ${text}`);
1006
+ }
1007
+
1008
+ /** The target's text matches the recorded pattern, in any case. */
1009
+ export async function expectMatches(target: Locator, source: string): Promise<void> {
1010
+ const re = pattern(source, "i");
1011
+ await poll(async () => {
1012
+ const text = await shown(target);
1013
+ return text !== "" && re.test(text);
1014
+ }, `target text to match /${source}/i`);
1015
+ }
1016
+
1017
+ /**
1018
+ * The attribute matches the pattern. A missing attribute holds only for an
1019
+ * absence check: a pattern that takes no value and "false" but not "true".
1020
+ */
1021
+ export async function expectAttribute(target: Locator, name: string, source: string): Promise<void> {
1022
+ const re = pattern(source);
1023
+ const absentHolds = re.test("") && re.test("false") && !re.test("true");
1024
+ await poll(async () => {
1025
+ const found = await target.first().getAttribute(name, { timeout: 1000 }).catch(() => undefined);
1026
+ if (found === undefined) return false;
1027
+ return found === null ? absentHolds : re.test(found);
1028
+ }, `attribute ${name} to match /${source}/`);
1029
+ }
1030
+
1031
+ /** Every match of every locator the recording names is hidden. */
1032
+ export async function expectNotVisible(...targets: Locator[]): Promise<void> {
1033
+ for (const target of targets) await expect(target.filter({ visible: true })).toHaveCount(0);
1034
+ }
1035
+
1036
+ /** Each value is shown in the container, as a whole line of its text. */
1037
+ export async function expectEach(container: Locator, values: string[]): Promise<void> {
1038
+ let missing = values;
1039
+ await poll(async () => {
1040
+ const lines = new Set((await shownLines(container)).map(normalize));
1041
+ missing = values.filter((v) => !lines.has(normalize(v)));
1042
+ return missing.length === 0;
1043
+ }, `every value to be shown`).catch((err) => {
1044
+ throw new Error(`${missing.map((v) => `"${v}"`).join(", ")} not shown in the target (${err})`);
1045
+ });
1046
+ }
1047
+
1048
+ async function shownLines(target: Locator): Promise<string[]> {
1049
+ const element = await target.first().elementHandle({ timeout: 1000 }).catch(() => null);
1050
+ return element ? lines(element).catch(() => []) : [];
1051
+ }
1052
+
1053
+ /** The active page's URL contains `expected`, raw, decoded, or with + read as a space. */
1054
+ export async function expectUrl(page: Page, expected: string | RegExp): Promise<void> {
1055
+ said(expected, "the expected URL");
1056
+ await poll(async () => {
1057
+ const url = page.url();
1058
+ return [url, decode(url), decode(url.replace(/\+/g, "%20"))].some((u) => contains(u, expected));
1059
+ }, `URL containing ${expected} on the active page`);
1060
+ }
1061
+
1062
+ // --- JSON field checks ----------------------------------------------------
1063
+
1064
+ /** A JSON field check, as a recording holds one (ResponseJsonCheck in saffron-ai). */
1065
+ export interface ResponseJsonCheck {
1066
+ /** JSON Pointer, for example /order/status or /items/0/sku. Empty selects the root. */
1067
+ path: string;
1068
+ equals?: string;
1069
+ type?: "string" | "number" | "boolean" | "null";
1070
+ exists?: boolean;
1071
+ /** The value at `path` is a list holding at least one item these checks all hold on. */
1072
+ item?: ResponseJsonCheck[];
1073
+ /** The value at `path` is a list with items, and these checks hold on each one. */
1074
+ every?: ResponseJsonCheck[];
1075
+ /** The value at `path` is a list of exactly this many items. */
1076
+ count?: string;
1077
+ /** The value at `path` is not this scalar (read as `type`). */
1078
+ differs?: string;
1079
+ /** The value at `path` is text matching this regular expression. */
1080
+ pattern?: string;
1081
+ /** The value at `path` is a number at least `min` and/or at most `max`. */
1082
+ min?: string;
1083
+ max?: string;
1084
+ }
1085
+
1086
+ // Saffron's own checker, src/util/response-json.ts in saffron-ai, copied
1087
+ // verbatim so an exported check reads a response exactly as replay does
1088
+ // (a test in saffron-ai fails when the two differ).
1089
+ /*RESPONSE_JSON*/
1090
+ /** The texts of a check a step's value may be written in: resolved at replay, and where a row's value is looked for. */
1091
+ export const JSON_CHECK_TEXTS = ["equals", "differs", "count", "min", "max", "pattern"] as const;
1092
+
1093
+ /** Every check, an item or every check's own checks after it, at any depth. */
1094
+ export function flatJsonChecks(checks: ResponseJsonCheck[] | undefined): ResponseJsonCheck[] {
1095
+ return (checks ?? []).flatMap((c) => [c, ...flatJsonChecks(c.item), ...flatJsonChecks(c.every)]);
1096
+ }
1097
+
1098
+ /** The checks rewritten by `map`, an item or every check's own checks too. */
1099
+ export function mapJsonChecks(checks: ResponseJsonCheck[], map: (check: ResponseJsonCheck) => ResponseJsonCheck): ResponseJsonCheck[] {
1100
+ return checks.map((c) => {
1101
+ const mapped = map(c);
1102
+ return { ...mapped, ...(c.item ? { item: mapJsonChecks(c.item, map) } : {}), ...(c.every ? { every: mapJsonChecks(c.every, map) } : {}) };
1103
+ });
1104
+ }
1105
+
1106
+ /** A check with its texts (JSON_CHECK_TEXTS) rewritten by `text`; a pattern by `pattern`, which defaults to `text`. */
1107
+ export function mapJsonCheckTexts(check: ResponseJsonCheck, text: (value: string) => string, pattern: (value: string) => string = text): ResponseJsonCheck {
1108
+ const out = { ...check };
1109
+ for (const field of JSON_CHECK_TEXTS) {
1110
+ const value = check[field];
1111
+ if (value !== undefined) out[field] = field === "pattern" ? pattern(value) : text(value);
1112
+ }
1113
+ return out;
1114
+ }
1115
+
1116
+ /** JSON Pointer keeps field names containing dots, slashes or brackets unambiguous. */
1117
+ export function responseJsonProblem(checks: unknown): string | undefined {
1118
+ if (!Array.isArray(checks) || checks.length === 0) return "must be a non-empty list of JSON field checks";
1119
+ for (const c of checks) {
1120
+ if (!c || typeof c !== "object" || typeof c.path !== "string" || !/^(?:\/(?:[^~]|~[01])*)*$/.test(c.path)) return "each path must be a JSON Pointer, such as /order/status or /items/0/sku";
1121
+ const kinds = ["equals", "exists", "item", "every", "count", "differs", "pattern"].filter((k) => c[k] !== undefined).length + (c.min !== undefined || c.max !== undefined ? 1 : 0);
1122
+ if (kinds !== 1) return "each check needs exactly one of equals, differs, exists, pattern, min and/or max, count, item or every";
1123
+ for (const list of ["item", "every"] as const) {
1124
+ if (c[list] !== undefined) {
1125
+ const inner = responseJsonProblem(c[list]);
1126
+ if (inner) return `${list} ${inner}`;
1127
+ }
1128
+ }
1129
+ for (const field of JSON_CHECK_TEXTS) if (c[field] !== undefined && typeof c[field] !== "string") return `${field} must be a string`;
1130
+ if (c.exists !== undefined && typeof c.exists !== "boolean") return "exists must be true or false";
1131
+ if (c.type !== undefined && (!["string", "number", "boolean", "null"].includes(c.type) || (c.equals === undefined && c.differs === undefined))) return "type must be string, number, boolean or null, on an equals or differs check";
1132
+ }
1133
+ }
1134
+
1135
+ /** The value a check compares with (`equals`, or the text given), read as the check's type. */
1136
+ export function jsonExpected(check: ResponseJsonCheck, text: string | undefined = check.equals): unknown {
1137
+ if (check.type === undefined || check.type === "string") return text;
1138
+ let value: unknown;
1139
+ try { value = JSON.parse(text!); } catch { /* Name the field without echoing a secret or JSON parse excerpt. */ }
1140
+ // Beyond 2^53 two different numbers parse equal: such a check would pass on another value.
1141
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
1142
+ throw new Error(`JSON field ${JSON.stringify(check.path)}: ${text} is too large to compare exactly as a number; check it as a string`);
1143
+ }
1144
+ if ((check.type === "null" ? value === null : typeof value === check.type) && (typeof value !== "number" || Number.isFinite(value))) return value;
1145
+ throw new Error(`JSON field ${JSON.stringify(check.path)}: expected value must be a valid ${check.type}`);
1146
+ }
1147
+
1148
+ /** A check's number (count, min, max) as a number, or why it is none. */
1149
+ function jsonNumber(check: ResponseJsonCheck, field: "count" | "min" | "max"): number {
1150
+ const text = check[field]!.trim();
1151
+ const value = Number(text);
1152
+ if (text === "" || !Number.isFinite(value) || (field === "count" && (!Number.isInteger(value) || value < 0))) throw new Error(`JSON field ${JSON.stringify(check.path)}: ${field} must be a ${field === "count" ? "whole number" : "number"}, got ${JSON.stringify(check[field])}`);
1153
+ return value;
1154
+ }
1155
+
1156
+ /** Every number a resolved check compares with must read as one: refused before the response is looked at. */
1157
+ export function jsonChecksReadable(checks: ResponseJsonCheck[]): void {
1158
+ for (const c of flatJsonChecks(checks)) {
1159
+ if (c.equals !== undefined) jsonExpected(c);
1160
+ if (c.differs !== undefined) jsonExpected(c, c.differs);
1161
+ for (const field of ["count", "min", "max"] as const) if (c[field] !== undefined) jsonNumber(c, field);
1162
+ if (c.pattern !== undefined) jsonPattern(c);
1163
+ }
1164
+ }
1165
+
1166
+ function jsonPattern(check: ResponseJsonCheck): RegExp {
1167
+ try {
1168
+ // A row value bounded in it (resolveTokens) needs unicode mode, as a browser pattern does.
1169
+ return patternRegex(check.pattern!);
1170
+ } catch {
1171
+ throw new Error(`JSON field ${JSON.stringify(check.path)}: pattern ${JSON.stringify(check.pattern)} is not a regular expression`);
1172
+ }
1173
+ }
1174
+
1175
+ const kind = (value: unknown) => value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
1176
+ const describe = (value: unknown) => `${kind(value)}${value === null || typeof value !== "object" ? ` ${JSON.stringify(value)}` : ""}`;
1177
+
1178
+ /** The value at a JSON Pointer: own properties and array indexes only, undefined when missing. */
1179
+ function at(json: unknown, path: string): unknown {
1180
+ let value = json;
1181
+ for (const part of path === "" ? [] : path.slice(1).split("/")) {
1182
+ const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
1183
+ value = value !== null && typeof value === "object" && (!Array.isArray(value) || /^(0|[1-9]\d*)$/.test(key)) && Object.hasOwn(value, key)
1184
+ ? (value as Record<string, unknown>)[key] : undefined;
1185
+ }
1186
+ return value;
1187
+ }
1188
+
1189
+ /** What an item check looks for, for a message: `name "ann", text present`. */
1190
+ const wanted = (checks: ResponseJsonCheck[]): string =>
1191
+ checks.map((c) => `${c.path || "the item"} ${
1192
+ c.item ? `holding an item with ${wanted(c.item)}`
1193
+ : c.every ? `every item with ${wanted(c.every)}`
1194
+ : c.exists !== undefined ? (c.exists ? "present" : "absent")
1195
+ : c.count !== undefined ? `of ${c.count} item(s)`
1196
+ : c.differs !== undefined ? `other than ${JSON.stringify(c.differs)}`
1197
+ : c.pattern !== undefined ? `matching /${c.pattern}/`
1198
+ : c.min !== undefined || c.max !== undefined ? [c.min !== undefined ? `at least ${c.min}` : "", c.max !== undefined ? `at most ${c.max}` : ""].filter(Boolean).join(" and ")
1199
+ : JSON.stringify(c.equals)}`).join(", ");
1200
+
1201
+ /** Why the checks do not hold on a parsed value, or undefined. */
1202
+ function checkValue(json: unknown, checks: ResponseJsonCheck[], prefix = ""): string | undefined {
1203
+ for (const check of checks) {
1204
+ const value = at(json, check.path);
1205
+ const field = `JSON field ${JSON.stringify(prefix + check.path)}`;
1206
+ const got = value === undefined ? "missing" : describe(value);
1207
+ if (check.item) {
1208
+ if (!Array.isArray(value)) return `${field}: expected a list, got ${got}`;
1209
+ if (!value.some((entry) => checkValue(entry, check.item!) === undefined)) return `${field}: none of its ${value.length} item(s) has ${wanted(check.item)}`;
1210
+ } else if (check.every) {
1211
+ // An empty list holds nothing: "every order is paid" over no orders is no check.
1212
+ if (!Array.isArray(value)) return `${field}: expected a list, got ${got}`;
1213
+ if (value.length === 0) return `${field}: expected a list with items, every one with ${wanted(check.every)}, got an empty list`;
1214
+ for (const [i, entry] of value.entries()) {
1215
+ const problem = checkValue(entry, check.every, `${prefix}${check.path}/${i}`);
1216
+ if (problem) return problem;
1217
+ }
1218
+ } else if (check.count !== undefined) {
1219
+ const expected = jsonNumber(check, "count");
1220
+ if (!Array.isArray(value)) return `${field}: expected a list, got ${got}`;
1221
+ if (value.length !== expected) return `${field}: expected ${expected} item(s), got ${value.length}`;
1222
+ } else if (check.exists !== undefined) {
1223
+ if ((value !== undefined) !== check.exists) return `${field}: expected ${check.exists ? "present, got missing" : `absent, got ${describe(value)}`}`;
1224
+ } else if (check.differs !== undefined) {
1225
+ const other = jsonExpected(check, check.differs);
1226
+ if (value === undefined) return `${field}: expected a value other than ${describe(other)}, got missing`;
1227
+ // Untyped, the text is compared as written: a number 5 is the same as "5" (a captured id is kept as text).
1228
+ if (value === other || (check.type === undefined && value !== null && typeof value !== "object" && String(value) === other)) return `${field}: expected a value other than ${describe(other)}, got the same`;
1229
+ } else if (check.pattern !== undefined) {
1230
+ const re = jsonPattern(check);
1231
+ if (typeof value !== "string") return `${field}: expected text matching /${check.pattern}/, got ${got}`;
1232
+ if (!re.test(value)) return `${field}: expected text matching /${check.pattern}/, got ${JSON.stringify(value)}`;
1233
+ } else if (check.min !== undefined || check.max !== undefined) {
1234
+ const min = check.min === undefined ? undefined : jsonNumber(check, "min");
1235
+ const max = check.max === undefined ? undefined : jsonNumber(check, "max");
1236
+ const bounds = [min !== undefined ? `at least ${min}` : "", max !== undefined ? `at most ${max}` : ""].filter(Boolean).join(" and ");
1237
+ if (typeof value !== "number") return `${field}: expected a number ${bounds}, got ${got}`;
1238
+ if ((min !== undefined && value < min) || (max !== undefined && value > max)) return `${field}: expected a number ${bounds}, got ${value}`;
1239
+ } else {
1240
+ const expected = jsonExpected(check);
1241
+ if (value !== expected) return `${field}: expected ${describe(expected)}, got ${got}`;
1242
+ }
1243
+ }
1244
+ return undefined;
1245
+ }
1246
+
1247
+ /** A missing property is different from a property whose value is null. */
1248
+ export function checkResponseJson(body: string | undefined, checks: ResponseJsonCheck[]): string | undefined {
1249
+ if (body === undefined) return "response body is pending, unreadable or not a supported text content type";
1250
+ let json: unknown;
1251
+ try { json = JSON.parse(body); } catch { return "response body is not valid JSON"; }
1252
+ return checkValue(json, checks);
1253
+ }
1254
+
1255
+ /** Unicode boundaries need unicode mode; preserve legacy flags on patterns without them. */
1256
+ export function patternRegex(source: string, flags = ""): RegExp {
1257
+ if (/[uv]/.test(flags) || source.includes(String.raw`[\p{L}\p{N}\p{M}]`)) {
1258
+ // Playwright escapes quotes and chain separators; unicode regexes use hex escapes.
1259
+ source = source.replace(/\\.|[\s\S]/g, part => /^\\['"`>\-]$/.test(part) ? `\\x${part.charCodeAt(1).toString(16)}` : part);
1260
+ if (!/[uv]/.test(flags)) flags += "u";
1261
+ }
1262
+ return new RegExp(source, flags);
1263
+ }
1264
+ /*END*/