@cronn/playwright-semantic-snapshots 0.0.0-stage → 0.36.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,268 @@
1
+ import { Expect, Locator, MatcherReturnType, Page } from "@playwright/test";
2
+ import { PlaywrightMatchJsonFileOptions, PlaywrightMatchTextFileOptions, PlaywrightValidationFileMatcherConfig } from "@cronn/playwright-file-snapshots";
3
+ import { MarkdownTableNormalizer } from "@cronn/lib-file-snapshots";
4
+ interface MarkdownTableSnapshotOptions {
5
+ /**
6
+ * Show sort indicator for column headers
7
+ *
8
+ * @default true
9
+ */
10
+ showSortIndicator?: boolean;
11
+ /**
12
+ * Custom normalizers to apply before serialization
13
+ */
14
+ normalizers?: Array<MarkdownTableNormalizer>;
15
+ }
16
+ /**
17
+ * Creates a Markdown table snapshot from a table or grid element
18
+ */
19
+ export declare function markdownTableSnapshot(locator: Locator, options?: MarkdownTableSnapshotOptions): Promise<string>;
20
+ interface DisableableAttributes {
21
+ disabled?: boolean;
22
+ }
23
+ interface SelectableAttributes {
24
+ selected?: boolean;
25
+ }
26
+ interface MultiselectableAttributes {
27
+ multiselectable?: boolean;
28
+ }
29
+ interface ExpandableAttributes {
30
+ expanded?: boolean;
31
+ }
32
+ interface CheckableAttributes {
33
+ checked?: CheckedValue;
34
+ }
35
+ type CheckedValue = true | "mixed";
36
+ interface DiscribableAttributes {
37
+ description?: string;
38
+ }
39
+ interface InputStateAttributes extends DisableableAttributes {
40
+ readonly?: boolean;
41
+ required?: boolean;
42
+ invalid?: boolean;
43
+ }
44
+ interface ButtonSnapshot extends GenericElementSnapshot<"button", ButtonAttributes> {}
45
+ interface ButtonAttributes extends DisableableAttributes, ExpandableAttributes {
46
+ pressed?: PressedValue;
47
+ }
48
+ type PressedValue = true | "mixed";
49
+ type SetValues<TSet> = TSet extends Set<infer TValue> ? TValue : never;
50
+ type PlaywrightTarget = Page | Locator;
51
+ declare const CONTAINER_ROLES: Set<"alert" | "article" | "banner" | "blockquote" | "code" | "complementary" | "contentinfo" | "definition" | "deletion" | "descriptionlist" | "emphasis" | "form" | "grid" | "insertion" | "label" | "list" | "listitem" | "log" | "main" | "mark" | "menu" | "navigation" | "note" | "paragraph" | "row" | "rowgroup" | "search" | "status" | "strong" | "subscript" | "superscript" | "table" | "tablist" | "tabpanel" | "term" | "toolbar" | "tree">;
52
+ interface ContainerSnapshot extends GenericElementSnapshot<ContainerRole> {}
53
+ type ContainerRole = SetValues<typeof CONTAINER_ROLES>;
54
+ interface RegionSnapshot extends GenericElementSnapshot<"region"> {}
55
+ interface DialogSnapshot extends GenericElementSnapshot<DialogRole, DialogAttributes> {}
56
+ type DialogRole = "dialog" | "alertdialog";
57
+ interface DialogAttributes extends DiscribableAttributes {
58
+ modal?: boolean;
59
+ }
60
+ interface GroupSnapshot extends GenericElementSnapshot<"group"> {}
61
+ interface RadioGroupSnapshot extends GenericElementSnapshot<"radiogroup", RadiogroupAttributes> {}
62
+ interface RadiogroupAttributes extends DiscribableAttributes {}
63
+ interface HeadingSnapshot extends GenericElementSnapshot<"heading", HeadingAttributes> {}
64
+ interface HeadingAttributes {
65
+ level?: number;
66
+ }
67
+ interface ImageSnapshot extends GenericElementSnapshot<"img"> {}
68
+ interface InputSnapshot extends GenericElementSnapshot<CommonInputRole, InputAttributes> {}
69
+ type InputRole = "combobox" | CommonInputRole;
70
+ type CommonInputRole = "button" | "checkbox" | "radio" | "searchbox" | "slider" | "spinbutton" | "textbox";
71
+ interface InputAttributes extends CommonInputAttributes, CheckableAttributes {
72
+ value?: string;
73
+ }
74
+ interface CommonInputAttributes extends InputStateAttributes, DiscribableAttributes {
75
+ placeholder?: string;
76
+ }
77
+ interface ComboboxSnapshot extends GenericElementSnapshot<"combobox", ComboboxAttributes> {}
78
+ interface SelectionInputAttributes extends CommonInputAttributes, ExpandableAttributes {}
79
+ interface ComboboxAttributes extends SelectionInputAttributes {
80
+ value?: string | Array<string>;
81
+ }
82
+ interface OptionSnapshot extends GenericElementSnapshot<"option", OptionAttributes> {}
83
+ interface OptionAttributes extends SelectableAttributes, DisableableAttributes {}
84
+ interface ListboxSnapshot extends GenericElementSnapshot<"listbox", ListboxAttributes> {}
85
+ interface ListboxAttributes extends SelectionInputAttributes, MultiselectableAttributes {}
86
+ interface LinkSnapshot extends GenericElementSnapshot<"link", LinkAttributes> {}
87
+ interface LinkAttributes {
88
+ url?: string;
89
+ current?: CurrentValue;
90
+ }
91
+ type CurrentValue = true | "page" | "step";
92
+ interface MenuItemSnapshot extends GenericElementSnapshot<"menuitem", MenuitemAttributes> {}
93
+ interface MenuitemAttributes extends LinkAttributes, DisableableAttributes {}
94
+ interface ProgressbarSnapshot extends GenericElementSnapshot<"progressbar", ProgressbarAttributes> {}
95
+ interface ProgressbarAttributes {
96
+ value?: number;
97
+ }
98
+ interface SeparatorSnapshot extends GenericElementSnapshot<"separator"> {}
99
+ interface TabSnapshot extends GenericElementSnapshot<"tab", TabAttributes> {}
100
+ interface TabAttributes extends DisableableAttributes, SelectableAttributes {}
101
+ declare const SORT_TYPES: Set<"ascending" | "descending" | "other">;
102
+ interface ColumnHeaderSnapshot extends GenericElementSnapshot<"columnheader", ColumnHeaderAttributes> {}
103
+ interface ColumnHeaderAttributes extends CellAttributes {
104
+ sort?: SortType;
105
+ }
106
+ type SortType = SetValues<typeof SORT_TYPES>;
107
+ interface CellSnapshot extends GenericElementSnapshot<CellRole, CellAttributes> {}
108
+ type CellRole = "columnheader" | "rowheader" | "cell" | "gridcell";
109
+ interface CellAttributes {
110
+ colSpan?: number;
111
+ rowSpan?: number;
112
+ }
113
+ interface TextSnapshot {
114
+ role: "text";
115
+ name: string;
116
+ }
117
+ interface TreeItemSnapshot extends GenericElementSnapshot<"treeitem", TreeItemAttributes> {}
118
+ interface TreeItemAttributes extends CheckableAttributes, DisableableAttributes, ExpandableAttributes, SelectableAttributes {}
119
+ type TextRole = "text";
120
+ type ElementRole = "button" | "group" | "heading" | "img" | "link" | "listbox" | "menuitem" | "option" | "progressbar" | "radiogroup" | "region" | "separator" | "tab" | "treeitem" | CellRole | ContainerRole | DialogRole | InputRole;
121
+ type NodeRole = ElementRole | TextRole;
122
+ type NodeSnapshot = ElementSnapshot | TextSnapshot;
123
+ type SnapshotByRole<TRole extends NodeRole> = NodeSnapshot & {
124
+ role: TRole;
125
+ };
126
+ interface GenericElementSnapshot<TRole extends ElementRole = ElementRole, TAttributes extends object = object> {
127
+ role: TRole;
128
+ name?: string;
129
+ attributes: TAttributes;
130
+ children: Array<NodeSnapshot>;
131
+ }
132
+ type ElementSnapshot = ButtonSnapshot | CellSnapshot | ColumnHeaderSnapshot | ComboboxSnapshot | ContainerSnapshot | DialogSnapshot | GroupSnapshot | HeadingSnapshot | ImageSnapshot | InputSnapshot | LinkSnapshot | ListboxSnapshot | OptionSnapshot | ProgressbarSnapshot | RegionSnapshot | TabSnapshot | MenuItemSnapshot | RadioGroupSnapshot | SeparatorSnapshot | TreeItemSnapshot;
133
+ type SnapshotTransformer = (snapshot: NodeSnapshot) => unknown;
134
+ type RoleBasedSnapshotTransformer<TRole extends NodeRole = NodeRole> = (snapshot: SnapshotByRole<TRole>, context: SnapshotTransformerContext) => unknown;
135
+ type DefaultSnapshotTransformer = (snapshot: NodeSnapshot, context: SnapshotTransformerContext) => unknown;
136
+ interface SnapshotTransformerContext {
137
+ transform: SnapshotTransformer;
138
+ }
139
+ type RoleBasedSnapshotTransformers = { [TRole in NodeRole]?: RoleBasedSnapshotTransformer<TRole>; };
140
+ type FilterPredicate = (snapshot: NodeSnapshot) => boolean;
141
+ type GuardedFilterPredicate<TSnapshot extends NodeSnapshot> = (snapshot: NodeSnapshot) => snapshot is TSnapshot;
142
+ interface FilterOptions extends FilterBaseOptions {
143
+ /**
144
+ * Include only elements in the snapshot for which the specified predicate returns `true`
145
+ */
146
+ predicate: FilterPredicate;
147
+ }
148
+ interface GuardedFilterOptions<TSnapshot extends NodeSnapshot> extends FilterBaseOptions {
149
+ /**
150
+ * Include only elements in the snapshot for which the specified predicate returns `true`
151
+ */
152
+ predicate: GuardedFilterPredicate<TSnapshot>;
153
+ }
154
+ interface FilterBaseOptions {
155
+ /**
156
+ * Array of snapshots to filter.
157
+ */
158
+ snapshots: Array<NodeSnapshot>;
159
+ /**
160
+ * Recursively apply specified filter to children of filtered elements
161
+ *
162
+ * By default, recursion ends when the filter returns `true` for an element.
163
+ * Should be `true` for filters intended to remove specific elements recursively.
164
+ *
165
+ * @default false
166
+ */
167
+ recurse?: boolean;
168
+ }
169
+ /**
170
+ * Filters node snapshots based on the provided predicate function
171
+ */
172
+ export declare function filter<TSnapshot extends NodeSnapshot = NodeSnapshot>(options: GuardedFilterOptions<TSnapshot>): Array<TSnapshot>;
173
+ export declare function filter(options: FilterOptions): Array<NodeSnapshot>;
174
+ /**
175
+ * Filters node snapshots by a specific role
176
+ */
177
+ export declare function filterByRole<TRole extends NodeRole>(role: TRole, snapshots: Array<NodeSnapshot>): Array<SnapshotByRole<TRole>>;
178
+ interface SemanticSnapshotOptions {
179
+ /**
180
+ * Include only elements in the snapshot for which the specified filter returns `true`
181
+ *
182
+ * @default () => true
183
+ */
184
+ filter?: FilterPredicate;
185
+ /**
186
+ * Recursively apply specified filter to children of filtered elements
187
+ *
188
+ * By default, recursion ends when the filter returns `true` for an element.
189
+ * Should be `true` for filters intended to remove specific elements recursively.
190
+ *
191
+ * @default false
192
+ */
193
+ recurseFilter?: boolean;
194
+ /**
195
+ * Replace the default transformation for specific roles
196
+ *
197
+ * Transformers are keyed by role and applied after the filter, but before
198
+ * the default serialization. A transformer may return any JSON-serializable
199
+ * value, which is written to the snapshot verbatim. The `transform` function
200
+ * of its context applies the default transformation to untransformed
201
+ * children.
202
+ */
203
+ transformers?: RoleBasedSnapshotTransformers;
204
+ /**
205
+ * Replace the default transformation for all roles
206
+ *
207
+ * Applied to every snapshot passed to the default transformation, including
208
+ * the ones a transformer delegates via the `transform` function of its
209
+ * context. Transformers registered for a role take precedence.
210
+ *
211
+ * @default semanticSnapshotTransformer
212
+ */
213
+ defaultTransformer?: DefaultSnapshotTransformer;
214
+ }
215
+ /**
216
+ * Captures a semantic snapshot of the specified locator's DOM structure.
217
+ *
218
+ * This function creates a raw snapshot of the DOM element identified by the locator
219
+ * and transforms it into a semantic representation using the provided options.
220
+ *
221
+ * @param target - The Page or Locator instance that identifies the DOM element to snapshot
222
+ * @param options - Optional configuration settings for controlling the snapshot behavior
223
+ * @return A promise that resolves to the semantic snapshot
224
+ */
225
+ export declare function semanticSnapshot(target: PlaywrightTarget, options?: SemanticSnapshotOptions): Promise<unknown>;
226
+ /**
227
+ * Captures a raw snapshot of the element matched by the provided locator.
228
+ *
229
+ * Returns an array of node snapshots representing the current state of the matched elements
230
+ * in the DOM, including their properties, attributes, and structure.
231
+ *
232
+ * @param target - The Page or Locator instance used to identify the target element to snapshot
233
+ * @return A promise that resolves to an array of NodeSnapshot objects representing the captured element
234
+ */
235
+ export declare function rawSnapshot(target: PlaywrightTarget): Promise<Array<NodeSnapshot>>;
236
+ interface SemanticSnapshotMatchers {
237
+ toMatchSemanticSnapshotFile: (actual: PlaywrightTarget, options?: MatchSemanticSnapshotFileOptions) => Promise<MatcherReturnType>;
238
+ toMatchMarkdownTableSnapshotFile: (actual: Locator, options?: MatchMarkdownTableSnapshotFileOptions) => Promise<MatcherReturnType>;
239
+ }
240
+ interface MatchSemanticSnapshotFileOptions extends PlaywrightMatchJsonFileOptions, SemanticSnapshotOptions {}
241
+ interface MatchMarkdownTableSnapshotFileOptions extends Omit<PlaywrightMatchTextFileOptions, "fileExtension" | "normalizers">, MarkdownTableSnapshotOptions {}
242
+ /**
243
+ * Defines a custom Playwright expect instance with semantic snapshot matchers for validating DOM elements against stored snapshots.
244
+ *
245
+ * @param {PlaywrightValidationFileMatcherConfig} config - Configuration options for file matching behavior
246
+ * @return {Expect<SemanticSnapshotMatchers>} An extended expect instance that includes matcher methods for semantic snapshot validation.
247
+ *
248
+ * @example
249
+ * export const expect = defineSemanticSnapshotMatchers();
250
+ *
251
+ * test("matches semantic snapshot", async ({ page }) => {
252
+ * await expect(page.getByRole("main")).toMatchSemanticSnapshotFile();
253
+ * });
254
+ */
255
+ export declare function defineSemanticSnapshotMatchers(config?: PlaywrightValidationFileMatcherConfig): Expect<SemanticSnapshotMatchers>;
256
+ /**
257
+ * Include only elements with the specified role
258
+ */
259
+ export declare function includeRole<TRole extends NodeRole>(role: TRole | Array<TRole>): GuardedFilterPredicate<SnapshotByRole<TRole>>;
260
+ /**
261
+ * Exclude elements with the specified role
262
+ */
263
+ export declare function excludeRole<TRole extends NodeRole>(role: TRole | Array<TRole>): GuardedFilterPredicate<SnapshotByRole<TRole>>;
264
+ /**
265
+ * Aggregates and normalizes the text content of all provided snapshots
266
+ */
267
+ export declare function getTextContent(snapshots: Array<NodeSnapshot>): string;
268
+ export type { ButtonSnapshot, CellSnapshot, ColumnHeaderSnapshot, ComboboxSnapshot, ContainerSnapshot, DefaultSnapshotTransformer, DialogSnapshot, ElementRole, ElementSnapshot, GroupSnapshot, HeadingSnapshot, ImageSnapshot, InputSnapshot, LinkSnapshot, ListboxSnapshot, MarkdownTableSnapshotOptions, MatchMarkdownTableSnapshotFileOptions, MatchSemanticSnapshotFileOptions, MenuItemSnapshot, NodeRole, NodeSnapshot, OptionSnapshot, ProgressbarSnapshot, RadioGroupSnapshot, RegionSnapshot, RoleBasedSnapshotTransformer, RoleBasedSnapshotTransformers, SemanticSnapshotMatchers, SemanticSnapshotOptions, SeparatorSnapshot, SnapshotByRole, SnapshotTransformer, SnapshotTransformerContext, TabSnapshot, TextSnapshot, TreeItemSnapshot };
package/dist/index.mjs ADDED
@@ -0,0 +1,331 @@
1
+ import { expect } from "@playwright/test";
2
+ import { defineJsonFileMatcher, defineTextFileMatcher } from "@cronn/playwright-file-snapshots";
3
+ import { MarkdownTableSerializer } from "@cronn/lib-file-snapshots";
4
+ import fs from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { packageDirectory } from "package-directory";
7
+ // src/utils/guards.ts
8
+ function isTextSnapshot(snapshot) {
9
+ return hasRole("text", snapshot);
10
+ }
11
+ function hasRole(role, snapshot) {
12
+ if (typeof role === "string") return role === snapshot.role;
13
+ return role.includes(snapshot.role);
14
+ }
15
+ function isEmpty(value) {
16
+ if (typeof value === "string" || Array.isArray(value)) return value.length === 0;
17
+ return Object.keys(value).length === 0;
18
+ }
19
+ // src/utils/predicates.ts
20
+ /**
21
+ * Include only elements with the specified role
22
+ */
23
+ function includeRole(role) {
24
+ return (snapshot) => hasRole(role, snapshot);
25
+ }
26
+ /**
27
+ * Exclude elements with the specified role
28
+ */
29
+ function excludeRole(role) {
30
+ return (snapshot) => !hasRole(role, snapshot);
31
+ }
32
+ // src/utils/filter.ts
33
+ function filter(options) {
34
+ const { predicate, snapshots, recurse = false } = options;
35
+ return snapshots.flatMap((snapshot) => {
36
+ const isFilteredIn = predicate(snapshot);
37
+ if (isFilteredIn && !recurse) return snapshot;
38
+ if (!isFilteredIn && recurse) return [];
39
+ const filteredChildren = hasChildren(snapshot) ? filter({
40
+ predicate,
41
+ snapshots: snapshot.children ?? [],
42
+ recurse
43
+ }) : [];
44
+ if (!isFilteredIn) return filteredChildren;
45
+ if (isTextSnapshot(snapshot)) return snapshot;
46
+ return {
47
+ ...snapshot,
48
+ children: filteredChildren
49
+ };
50
+ });
51
+ }
52
+ /**
53
+ * Filters node snapshots by a specific role
54
+ */
55
+ function filterByRole(role, snapshots) {
56
+ return filter({
57
+ predicate: includeRole(role),
58
+ recurse: false,
59
+ snapshots
60
+ });
61
+ }
62
+ function hasChildren(snapshot) {
63
+ return "children" in snapshot && snapshot.children.length > 0;
64
+ }
65
+ // src/playwright/proxy.ts
66
+ var ElementSnapshotProxy = class ElementSnapshotProxy {
67
+ static browserLibSource = void 0;
68
+ async snapshotElement(locator) {
69
+ if (!await this.isLibraryLoaded(locator)) await this.loadLibrary(await this.resolveOwnerFrame(locator));
70
+ return await locator.evaluate((element) => {
71
+ return window.snapshotElement(element);
72
+ });
73
+ }
74
+ async isLibraryLoaded(locator) {
75
+ return await locator.evaluate(() => typeof window.snapshotElement === "function");
76
+ }
77
+ async resolveOwnerFrame(locator) {
78
+ const elementHandle = await locator.elementHandle();
79
+ try {
80
+ const frame = await elementHandle.ownerFrame();
81
+ if (frame === null) throw new Error("Unable to resolve frame of element");
82
+ return frame;
83
+ } finally {
84
+ await elementHandle.dispose();
85
+ }
86
+ }
87
+ async loadLibrary(frame) {
88
+ ElementSnapshotProxy.browserLibSource ??= await this.readBrowserLibSource();
89
+ await frame.evaluate(ElementSnapshotProxy.browserLibSource);
90
+ }
91
+ async readBrowserLibSource() {
92
+ const libPath = await this.resolveFromPackageRoot("dist", "browser-lib.iife.js");
93
+ return await fs.readFile(libPath, "utf8");
94
+ }
95
+ async resolveFromPackageRoot(...paths) {
96
+ const packageRoot = await packageDirectory({ cwd: import.meta.dirname });
97
+ if (packageRoot === void 0) throw new Error("Unable to resolve root directory of package");
98
+ return path.resolve(packageRoot, ...paths);
99
+ }
100
+ };
101
+ // src/utils/array.ts
102
+ function unwrapSingleItem(items) {
103
+ return items.length === 1 ? items.at(0) : items;
104
+ }
105
+ // src/transformers/semantic-snapshot-transformer.ts
106
+ function semanticSnapshotTransformer(snapshot, context) {
107
+ if (snapshot.role === "text") return snapshot.name;
108
+ return transformElementSnapshot(snapshot, context.transform);
109
+ }
110
+ function transformElementSnapshot(snapshot, transformRecursive) {
111
+ const normalizedSnapshot = normalizeElementSnapshot(snapshot, transformRecursive);
112
+ if (hasOnlyRole(normalizedSnapshot)) {
113
+ const { role } = normalizedSnapshot;
114
+ return transformedSnapshot(role, "");
115
+ }
116
+ if (hasOnlyName(normalizedSnapshot)) {
117
+ const { role, name } = normalizedSnapshot;
118
+ return transformedSnapshot(role, name);
119
+ }
120
+ if (hasOnlyChildren(normalizedSnapshot)) {
121
+ const { role, children } = normalizedSnapshot;
122
+ return transformedSnapshot(role, unwrapSingleItem(children));
123
+ }
124
+ const { role, name, attributes, children } = normalizedSnapshot;
125
+ return transformedSnapshot(role, name, {
126
+ ...attributes,
127
+ children: isEmpty(children) ? void 0 : unwrapSingleItem(children)
128
+ });
129
+ }
130
+ function normalizeElementSnapshot(snapshot, transformRecursive) {
131
+ const normalizedName = snapshot.name ?? "";
132
+ const transformedAttributes = transformAttributes(snapshot.attributes ?? {});
133
+ const transformedChildren = (snapshot.children ?? []).map(transformRecursive);
134
+ const singleChild = transformedChildren.length === 1 ? transformedChildren.at(0) : void 0;
135
+ const nameEqualsChildren = normalizedName === singleChild;
136
+ const valueEqualsChildren = typeof transformedAttributes.value === "string" && transformedAttributes.value === singleChild;
137
+ return {
138
+ role: snapshot.role,
139
+ name: normalizedName,
140
+ attributes: transformedAttributes,
141
+ children: nameEqualsChildren || valueEqualsChildren ? [] : transformedChildren
142
+ };
143
+ }
144
+ function hasOnlyRole(snapshot) {
145
+ return isEmpty(snapshot.name) && isEmpty(snapshot.attributes) && isEmpty(snapshot.children);
146
+ }
147
+ function hasOnlyName(snapshot) {
148
+ return !isEmpty(snapshot.name) && isEmpty(snapshot.attributes) && isEmpty(snapshot.children);
149
+ }
150
+ function hasOnlyChildren(snapshot) {
151
+ return isEmpty(snapshot.name) && isEmpty(snapshot.attributes) && !isEmpty(snapshot.children);
152
+ }
153
+ function transformAttributes(attributes) {
154
+ const filteredAttributes = {};
155
+ Object.entries(attributes).forEach(([attributeName, attributeValue]) => {
156
+ if (attributeValue === void 0) return;
157
+ filteredAttributes[attributeName] = attributeValue;
158
+ });
159
+ return filteredAttributes;
160
+ }
161
+ function transformedSnapshot(role, nameOrContent, additionalProperties) {
162
+ return {
163
+ [role]: nameOrContent,
164
+ ...additionalProperties
165
+ };
166
+ }
167
+ // src/playwright/snapshot-serializer.ts
168
+ var SnapshotSerializer = class {
169
+ filter;
170
+ recurseFilter;
171
+ transformers;
172
+ defaultTransformer;
173
+ constructor(options = {}) {
174
+ this.filter = options.filter;
175
+ this.recurseFilter = options.recurseFilter ?? false;
176
+ this.transformers = { ...options.transformers };
177
+ this.defaultTransformer = options.defaultTransformer ?? semanticSnapshotTransformer;
178
+ }
179
+ transform(snapshots) {
180
+ return unwrapSingleItem(this.filterSnapshots(snapshots).map(this.transformSnapshotRecursive));
181
+ }
182
+ filterSnapshots(snapshots) {
183
+ if (this.filter === void 0) return snapshots;
184
+ return filter({
185
+ predicate: this.filter,
186
+ snapshots,
187
+ recurse: this.recurseFilter
188
+ });
189
+ }
190
+ boundDefaultTransformer = (snapshot) => this.defaultTransformer(snapshot, { transform: this.transformSnapshotRecursive });
191
+ transformSnapshotRecursive = (snapshot) => {
192
+ const transformer = this.transformers[snapshot.role];
193
+ if (transformer !== void 0) return transformer(snapshot, { transform: this.boundDefaultTransformer });
194
+ return this.defaultTransformer(snapshot, { transform: this.transformSnapshotRecursive });
195
+ };
196
+ };
197
+ // src/playwright/snapshot.ts
198
+ /**
199
+ * Captures a semantic snapshot of the specified locator's DOM structure.
200
+ *
201
+ * This function creates a raw snapshot of the DOM element identified by the locator
202
+ * and transforms it into a semantic representation using the provided options.
203
+ *
204
+ * @param target - The Page or Locator instance that identifies the DOM element to snapshot
205
+ * @param options - Optional configuration settings for controlling the snapshot behavior
206
+ * @return A promise that resolves to the semantic snapshot
207
+ */
208
+ async function semanticSnapshot(target, options) {
209
+ const snapshot = await rawSnapshot(target);
210
+ return new SnapshotSerializer(options).transform(snapshot);
211
+ }
212
+ /**
213
+ * Captures a raw snapshot of the element matched by the provided locator.
214
+ *
215
+ * Returns an array of node snapshots representing the current state of the matched elements
216
+ * in the DOM, including their properties, attributes, and structure.
217
+ *
218
+ * @param target - The Page or Locator instance used to identify the target element to snapshot
219
+ * @return A promise that resolves to an array of NodeSnapshot objects representing the captured element
220
+ */
221
+ async function rawSnapshot(target) {
222
+ const locator = isPage(target) ? target.locator("body") : target;
223
+ return await new ElementSnapshotProxy().snapshotElement(locator);
224
+ }
225
+ function isPage(target) {
226
+ return "goto" in target && typeof target.goto === "function";
227
+ }
228
+ // src/playwright/markdown-table.ts
229
+ const tableRoles = ["table", "grid"];
230
+ const cellRoles = [
231
+ "rowheader",
232
+ "cell",
233
+ "gridcell"
234
+ ];
235
+ const sortIndicators = {
236
+ ascending: "⯅",
237
+ descending: "⯆",
238
+ other: "⯁"
239
+ };
240
+ /**
241
+ * Creates a Markdown table snapshot from a table or grid element
242
+ */
243
+ async function markdownTableSnapshot(locator, options = {}) {
244
+ const { showSortIndicator, normalizers } = options;
245
+ const parsedTable = parseTable(await rawSnapshot(locator), { showSortIndicator });
246
+ return new MarkdownTableSerializer({ normalizers }).serialize(parsedTable);
247
+ }
248
+ function parseTable(snapshot, options) {
249
+ const { showSortIndicator = true } = options;
250
+ const tableOrGridResult = filter({
251
+ predicate: includeRole(tableRoles),
252
+ snapshots: snapshot
253
+ });
254
+ if (tableOrGridResult.length > 1) throw new Error("Multiple tables or grids found");
255
+ const [tableOrGrid] = tableOrGridResult;
256
+ if (tableOrGrid === void 0) throw new Error("No table or grid found");
257
+ const [headerRow, ...bodyRows] = filterByRole("row", tableOrGrid.children);
258
+ if (headerRow === void 0) throw new Error("No header row found");
259
+ const columnHeaders = filterByRole("columnheader", headerRow.children);
260
+ if (columnHeaders.length === 0) throw new Error("No column headers found");
261
+ return {
262
+ columns: columnHeaders.map((columnHeader) => getColumnHeaderText(columnHeader, showSortIndicator)),
263
+ rows: bodyRows.map(getCellTexts)
264
+ };
265
+ }
266
+ function getColumnHeaderText(columnHeader, showSortIndicator) {
267
+ const headerText = getNameOrDefault(columnHeader);
268
+ const sortType = columnHeader.attributes.sort;
269
+ if (!showSortIndicator || sortType === void 0) return headerText;
270
+ return `${headerText} ${sortIndicators[sortType]}`;
271
+ }
272
+ function getCellTexts(row) {
273
+ return filter({
274
+ predicate: includeRole(cellRoles),
275
+ snapshots: row.children
276
+ }).map(getNameOrDefault);
277
+ }
278
+ function getNameOrDefault(snapshot) {
279
+ return snapshot.name ?? "";
280
+ }
281
+ // src/playwright/matchers.ts
282
+ /**
283
+ * Defines a custom Playwright expect instance with semantic snapshot matchers for validating DOM elements against stored snapshots.
284
+ *
285
+ * @param {PlaywrightValidationFileMatcherConfig} config - Configuration options for file matching behavior
286
+ * @return {Expect<SemanticSnapshotMatchers>} An extended expect instance that includes matcher methods for semantic snapshot validation.
287
+ *
288
+ * @example
289
+ * export const expect = defineSemanticSnapshotMatchers();
290
+ *
291
+ * test("matches semantic snapshot", async ({ page }) => {
292
+ * await expect(page.getByRole("main")).toMatchSemanticSnapshotFile();
293
+ * });
294
+ */
295
+ function defineSemanticSnapshotMatchers(config = {}) {
296
+ async function toMatchSemanticSnapshotFile(actual, options = {}) {
297
+ return await defineJsonFileMatcher("toMatchSemanticSnapshotFile", config).bind(this)(() => semanticSnapshot(actual, options), options);
298
+ }
299
+ async function toMatchMarkdownTableSnapshotFile(actual, options = {}) {
300
+ const toMatchTextFile = defineTextFileMatcher("toMatchMarkdownTableSnapshotFile", config).bind(this);
301
+ const { showSortIndicator, normalizers, ...matchFileOptions } = options;
302
+ return await toMatchTextFile(() => markdownTableSnapshot(actual, {
303
+ showSortIndicator,
304
+ normalizers
305
+ }), {
306
+ ...matchFileOptions,
307
+ fileExtension: "md"
308
+ });
309
+ }
310
+ return expect.extend({
311
+ toMatchSemanticSnapshotFile,
312
+ toMatchMarkdownTableSnapshotFile
313
+ });
314
+ }
315
+ // src/utils/text.ts
316
+ /**
317
+ * Aggregates and normalizes the text content of all provided snapshots
318
+ */
319
+ function getTextContent(snapshots) {
320
+ return mergeTexts(filter({
321
+ snapshots,
322
+ predicate: isTextSnapshot
323
+ }));
324
+ }
325
+ function normalizeText(text) {
326
+ return text.replaceAll(/\s+/g, " ").trim();
327
+ }
328
+ function mergeTexts(texts) {
329
+ return normalizeText(texts.map((textNode) => textNode.name).join(" "));
330
+ }
331
+ export { defineSemanticSnapshotMatchers, excludeRole, filter, filterByRole, getTextContent, includeRole, markdownTableSnapshot, rawSnapshot, semanticSnapshot };
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
2
  "name": "@cronn/playwright-semantic-snapshots",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.36.0",
4
+ "description": "Semantic snapshots for Playwright",
5
+ "homepage": "https://cronn.github.io/file-snapshots/playwright/semantic-snapshots/",
6
+ "bugs": {
7
+ "url": "https://github.com/cronn/file-snapshots/issues"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "author": "cronn",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/cronn/file-snapshots.git",
14
+ "directory": "packages/playwright-semantic-snapshots"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "type": "module",
20
+ "exports": {
21
+ "./package.json": "./package.json",
22
+ ".": {
23
+ "types": "./dist/index.d.mts",
24
+ "default": "./dist/index.mjs"
25
+ }
26
+ },
27
+ "dependencies": {
28
+ "@cronn/lib-file-snapshots": "1.3.1",
29
+ "@cronn/playwright-file-snapshots": "2.4.1",
30
+ "package-directory": "^8.2.0"
31
+ },
32
+ "devDependencies": {
33
+ "@arethetypeswrong/core": "0.18.5",
34
+ "@cronn/file-snapshots-cli": "1.0.0",
35
+ "@cronn/shared-configs": "0.0.0",
36
+ "@cronn/test-utils": "0.0.0",
37
+ "@cronn/vitest-file-snapshots": "3.1.1",
38
+ "@playwright/test": "1.65.1",
39
+ "@types/node": "26.6.6",
40
+ "@typescript/native": "npm:typescript@^7.0.2",
41
+ "@vitest/coverage-v8": "5.1.1",
42
+ "oxlint": "1.94.0",
43
+ "oxlint-tsgolint": "7.0.2008",
44
+ "publint": "0.3.25",
45
+ "rimraf": "6.1.4",
46
+ "tsdown": "0.23.7",
47
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
48
+ "vitest": "5.1.1"
49
+ },
50
+ "peerDependencies": {
51
+ "@playwright/test": "^1.55"
52
+ },
53
+ "devEngines": {
54
+ "packageManager": {
55
+ "name": "pnpm",
56
+ "version": "12.23.0",
57
+ "onFail": "download"
58
+ },
59
+ "runtime": {
60
+ "name": "node",
61
+ "version": "26.13.1",
62
+ "onFail": "download"
63
+ }
64
+ },
65
+ "engines": {
66
+ "node": "^24.8.0 || >=26"
67
+ },
68
+ "scripts": {
69
+ "build": "tsdown",
70
+ "clean": "rimraf .turbo dist playwright-report test-results coverage",
71
+ "compile": "tsc",
72
+ "lint:check": "oxlint src/ tests/",
73
+ "lint:fix": "oxlint src/ tests/ --fix",
74
+ "playwright:install": "playwright install chromium",
75
+ "snapshots:check": "file-snapshots check --dir data/unit-test --dir data/integration-test",
76
+ "test:integration": "playwright test",
77
+ "test:unit": "vitest run",
78
+ "test:unit:coverage": "vitest run --coverage"
79
+ }
6
80
  }