@unframework.dev/testing 0.0.0-stage → 0.0.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.
Files changed (131) hide show
  1. package/README.md +511 -2
  2. package/dist/browser/axe.js +34 -0
  3. package/dist/browser/behaviour.js +59 -0
  4. package/dist/browser/capabilities.js +58 -0
  5. package/dist/browser/clock.d.ts +17 -0
  6. package/dist/browser/clock.js +69 -0
  7. package/dist/browser/console.d.ts +27 -0
  8. package/dist/browser/console.js +142 -0
  9. package/dist/browser/determinism.js +108 -0
  10. package/dist/browser/element-timeout.js +28 -0
  11. package/dist/browser/events.js +68 -0
  12. package/dist/browser/geometry.js +135 -0
  13. package/dist/browser/keys.js +62 -0
  14. package/dist/browser/matchers.d.ts +39 -0
  15. package/dist/browser/matchers.js +78 -0
  16. package/dist/browser/navigation.js +38 -0
  17. package/dist/browser/parity.d.ts +10 -0
  18. package/dist/browser/parity.js +93 -0
  19. package/dist/browser/spec.d.ts +25 -0
  20. package/dist/browser/spec.js +38 -0
  21. package/dist/browser/target.d.ts +16 -0
  22. package/dist/browser/target.js +27 -0
  23. package/dist/browser/text-runs.js +68 -0
  24. package/dist/browser/thrown.js +71 -0
  25. package/dist/browser/trace.d.ts +21 -0
  26. package/dist/browser/trace.js +73 -0
  27. package/dist/browser/user.d.ts +45 -0
  28. package/dist/browser/user.js +184 -0
  29. package/dist/browser/view.d.ts +114 -0
  30. package/dist/browser/view.js +282 -0
  31. package/dist/browser/visual.d.ts +20 -0
  32. package/dist/browser/visual.js +36 -0
  33. package/dist/cli.d.ts +23 -0
  34. package/dist/cli.js +90 -0
  35. package/dist/commands.d.ts +107 -0
  36. package/dist/config/broadcast.js +29 -0
  37. package/dist/config/cases.d.ts +28 -0
  38. package/dist/config/cases.js +94 -0
  39. package/dist/config/index.d.ts +81 -0
  40. package/dist/config/index.js +275 -0
  41. package/dist/diff.d.ts +14 -0
  42. package/dist/diff.js +92 -0
  43. package/dist/dom/serialize.js +236 -0
  44. package/dist/errors.d.ts +13 -0
  45. package/dist/errors.js +38 -0
  46. package/dist/harness.d.ts +184 -0
  47. package/dist/harness.js +53 -0
  48. package/dist/index.d.ts +16 -0
  49. package/dist/index.js +12 -0
  50. package/dist/internal.d.ts +8 -0
  51. package/dist/internal.js +6 -0
  52. package/dist/layers.d.ts +183 -0
  53. package/dist/layers.js +241 -0
  54. package/dist/node/browser.d.ts +33 -0
  55. package/dist/node/browser.js +64 -0
  56. package/dist/node/commands.d.ts +137 -0
  57. package/dist/node/commands.js +139 -0
  58. package/dist/node/context.d.ts +28 -0
  59. package/dist/node/context.js +55 -0
  60. package/dist/node/events.d.ts +25 -0
  61. package/dist/node/events.js +50 -0
  62. package/dist/node/finished.d.ts +12 -0
  63. package/dist/node/finished.js +28 -0
  64. package/dist/node/index.d.ts +21 -0
  65. package/dist/node/index.js +20 -0
  66. package/dist/node/matrix.d.ts +219 -0
  67. package/dist/node/matrix.js +309 -0
  68. package/dist/node/mode.d.ts +101 -0
  69. package/dist/node/mode.js +201 -0
  70. package/dist/node/names.d.ts +4 -0
  71. package/dist/node/names.js +5 -0
  72. package/dist/node/policy.d.ts +44 -0
  73. package/dist/node/policy.js +140 -0
  74. package/dist/node/reporter.d.ts +101 -0
  75. package/dist/node/reporter.js +251 -0
  76. package/dist/node/summary.d.ts +99 -0
  77. package/dist/node/summary.js +352 -0
  78. package/dist/node/thrown.js +78 -0
  79. package/dist/node/viewport.d.ts +7 -0
  80. package/dist/node/viewport.js +8 -0
  81. package/dist/node/visual.d.ts +85 -0
  82. package/dist/node/visual.js +370 -0
  83. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/protocol.d.ts +23930 -0
  84. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/structs.d.ts +22 -0
  85. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/types.d.ts +22221 -0
  86. package/dist/normalize/display.js +309 -0
  87. package/dist/normalize/index.d.ts +34 -0
  88. package/dist/normalize/index.js +38 -0
  89. package/dist/normalize/pipeline.d.ts +19 -0
  90. package/dist/normalize/pipeline.js +45 -0
  91. package/dist/normalize/print.js +103 -0
  92. package/dist/normalize/rules/angular-hosts.js +53 -0
  93. package/dist/normalize/rules/aria-hosts.js +48 -0
  94. package/dist/normalize/rules/comments.js +16 -0
  95. package/dist/normalize/rules/control-values.js +65 -0
  96. package/dist/normalize/rules/engine-aliases.js +34 -0
  97. package/dist/normalize/rules/framework-attributes.js +85 -0
  98. package/dist/normalize/rules/generated-ids.js +64 -0
  99. package/dist/normalize/rules/ordering.js +39 -0
  100. package/dist/normalize/rules/qwik-styles.js +21 -0
  101. package/dist/normalize/rules/qwik-templates.js +20 -0
  102. package/dist/normalize/rules/values.js +125 -0
  103. package/dist/normalize/rules/whitespace.js +381 -0
  104. package/dist/normalize/style.js +121 -0
  105. package/dist/normalize/targets.d.ts +8 -0
  106. package/dist/normalize/targets.js +17 -0
  107. package/dist/normalize/tree.d.ts +1 -0
  108. package/dist/normalize/tree.js +151 -0
  109. package/dist/setup.d.ts +1 -0
  110. package/dist/setup.js +149 -0
  111. package/dist/ssr/index.d.ts +10 -0
  112. package/dist/ssr/index.js +103 -0
  113. package/dist/ssr/spec.d.ts +1 -0
  114. package/dist/ssr/spec.js +7 -0
  115. package/dist/targets/angular.d.ts +1 -0
  116. package/dist/targets/angular.js +5 -0
  117. package/dist/targets/astro.d.ts +1 -0
  118. package/dist/targets/astro.js +5 -0
  119. package/dist/targets/qwik.d.ts +1 -0
  120. package/dist/targets/qwik.js +5 -0
  121. package/dist/targets/react.d.ts +1 -0
  122. package/dist/targets/react.js +5 -0
  123. package/dist/targets/solid.d.ts +1 -0
  124. package/dist/targets/solid.js +5 -0
  125. package/dist/targets/svelte.d.ts +1 -0
  126. package/dist/targets/svelte.js +5 -0
  127. package/dist/targets/vue.d.ts +1 -0
  128. package/dist/targets/vue.js +5 -0
  129. package/dist/visual-types.d.ts +92 -0
  130. package/dist/visual-types.js +24 -0
  131. package/package.json +135 -3
@@ -0,0 +1,275 @@
1
+ import { caseReferences } from "../harness.js";
2
+ import { recordCompiledModule } from "../node/events.js";
3
+ import { createHarnessRun, groupOrder, resolveHarnessMode } from "../node/mode.js";
4
+ import { parityBrowser } from "../node/browser.js";
5
+ import { ufMapStack } from "../node/thrown.js";
6
+ import { noErrorBroadcast } from "./broadcast.js";
7
+ import { EXCLUDED, discoverCases } from "./cases.js";
8
+ import { realpathSync } from "node:fs";
9
+ import { join, resolve } from "node:path";
10
+ import { TARGET_NAMES, builtinTargets, loadConfig, resolveConfig } from "@unframework.dev/compiler";
11
+ import { fileURLToPath } from "node:url";
12
+ import { mergeConfig } from "vitest/config";
13
+ //#region src/config/index.ts
14
+ /** The test files a project's run finds by default. */
15
+ const DEFAULT_INCLUDE = ["**/*.test.ts"];
16
+ /**
17
+ * This package's modules, wherever a project installs it: the server render comparison imports
18
+ * each case's main source, which must go through the project's Vite pipeline.
19
+ */
20
+ const TESTING_PACKAGE = /[\\/]node_modules[\\/]@unframework\.dev[\\/]testing[\\/]/;
21
+ /**
22
+ * The target packages' modules, wherever a project installs them: a server renderer imports its
23
+ * framework, which must be the copy the component the project's Vite pipeline compiles imports.
24
+ */
25
+ const TARGET_PACKAGES = /[\\/]node_modules[\\/]@unframework\.dev[\\/]target-[a-z]+[\\/]/;
26
+ /** How long a test runs at most: a cold browser project's first mount compiles its framework. */
27
+ const TEST_TIMEOUT = 6e4;
28
+ /**
29
+ * The Vitest configuration of a project's tests: one `browser:<target>` project in Chromium and
30
+ * one `ssr:<target>` project per target, with the reference ordered first. `UF_TARGETS` narrows
31
+ * the targets (`unframework test --target`), and `UF_UPDATE=1` writes the expectations
32
+ * (`--update`). Throws, naming the fix, on an invalid configuration, an unknown target, a case it
33
+ * cannot tell apart and a toolchain that cannot load: a check that cannot start fails.
34
+ */
35
+ async function defineTestConfig(options = {}) {
36
+ const root = realpathSync(options.root ?? process.cwd());
37
+ const config = await projectConfig(root);
38
+ const targets = options.targets ?? config.targets;
39
+ checkTargets("targets", targets, TARGET_NAMES);
40
+ const reference = options.reference ?? (targets.includes("vue") ? "vue" : targets[0]);
41
+ if (reference === void 0) throw new Error("[uf] defineTestConfig: the project has no target.");
42
+ checkTargets("reference", [reference], targets);
43
+ const mode = resolveHarnessMode({
44
+ env: process.env,
45
+ platform: process.platform,
46
+ argv: process.env.UF_TEST_CLI === "1" ? [] : process.argv,
47
+ project: { pixels: options.pixels ?? "live" }
48
+ });
49
+ if (mode.browser !== "chromium") throw new Error(`[uf] A project's tests run in Chromium alone: UF_BROWSER=${mode.browser} cannot apply.`);
50
+ const include = options.include ?? DEFAULT_INCLUDE;
51
+ const cases = discoverCases({
52
+ root,
53
+ include
54
+ });
55
+ if (!cases.length) throw new Error(`[uf] No test file under ${root} matches ${include.join(", ")}: a case is a directory with one test file, such as test/button/button.test.ts.`);
56
+ const harness = createHarnessRun({
57
+ root,
58
+ casesDir: root,
59
+ reference,
60
+ mode,
61
+ quarantine: [],
62
+ cases: Object.fromEntries(cases.map((info) => [info.id, info.config])),
63
+ updateCommand: "unframework test --update"
64
+ });
65
+ const named = caseReferences(harness);
66
+ checkTargets("a case's reference", named, targets);
67
+ const run = runTargets(targets, selectedTargets(process.env.UF_TARGETS, targets), [reference, ...named]);
68
+ const setup = {
69
+ root,
70
+ harness,
71
+ mode,
72
+ cases,
73
+ targets: run,
74
+ toolchainDir: (target) => toolchainDirOf(target, root, options.toolchainDirs, config.package?.resolveFrom)
75
+ };
76
+ return { test: { projects: await Promise.all(run.flatMap((target) => [browserProject(setup, target), ssrProject(setup, target)])) } };
77
+ }
78
+ /** The project's `unframework.config.ts`, resolved, or an error that lists its diagnostics. */
79
+ async function projectConfig(root) {
80
+ const loaded = await loadConfig(root);
81
+ const resolved = loaded.raw === void 0 ? {
82
+ config: void 0,
83
+ diagnostics: []
84
+ } : await resolveConfig(loaded.raw, loaded);
85
+ const diagnostics = [...loaded.diagnostics, ...resolved.diagnostics];
86
+ if (!resolved.config || diagnostics.some((each) => each.severity === "error")) throw new Error(`[uf] ${loaded.file ?? "unframework.config.ts"} is invalid:\n ${diagnostics.map((each) => `${each.code} ${each.message}`).join("\n ")}`);
87
+ return resolved.config;
88
+ }
89
+ /** Throws unless every name is one of `allowed`. */
90
+ function checkTargets(what, names, allowed) {
91
+ const unknown = names.filter((name) => !allowed.includes(name));
92
+ if (unknown.length) throw new Error(`[uf] defineTestConfig: ${what} names ${unknown.join(", ")}, which ${unknown.length > 1 ? "are" : "is"} not among ${allowed === TARGET_NAMES ? "the targets" : "the project's targets"} (${allowed.join(", ")}).`);
93
+ }
94
+ /**
95
+ * The targets `UF_TARGETS` selects (`unframework test --target`), every one of the project's when
96
+ * it is unset. A name outside the project's targets throws, so a typo never tests nothing.
97
+ */
98
+ function selectedTargets(value, targets) {
99
+ if (!value?.trim()) return [...targets];
100
+ const requested = value.split(",").map((name) => name.trim()).filter(Boolean);
101
+ const unknown = requested.filter((name) => !targets.includes(name));
102
+ if (unknown.length) throw new Error(`[uf] UF_TARGETS names ${unknown.join(", ")}, which ${unknown.length > 1 ? "are" : "is"} not among the project's targets (${targets.join(", ")}).`);
103
+ return targets.filter((name) => requested.includes(name));
104
+ }
105
+ /**
106
+ * The targets a run tests, in the project's order: the selected ones, and the reference and every
107
+ * target a case names as its own, which write the expectations and the live captures the others
108
+ * compare with (ADR-0057), so they always join.
109
+ */
110
+ function runTargets(targets, selected, writers) {
111
+ return targets.filter((name) => selected.includes(name) || writers.includes(name));
112
+ }
113
+ /**
114
+ * Where a target's compiler stack resolves from: `toolchainDirs`, relative to the root, then
115
+ * `package.resolveFrom`, which `resolveConfig` has made absolute, then the root (A9).
116
+ */
117
+ function toolchainDirOf(target, root, toolchainDirs, resolveFrom) {
118
+ const own = toolchainDirs?.[target];
119
+ if (own !== void 0) return resolve(root, own);
120
+ return (typeof resolveFrom === "string" ? resolveFrom : resolveFrom?.[target]) ?? root;
121
+ }
122
+ function group(setup, kind, target) {
123
+ return groupOrder(kind, target, setup.mode, setup.harness.reference, caseReferences(setup.harness), setup.targets);
124
+ }
125
+ /** Each target's toolchain, loaded when its projects are built, so a run loads only its own. */
126
+ const TOOLCHAINS = {
127
+ react: () => import("@unframework.dev/target-react/toolchain"),
128
+ vue: () => import("@unframework.dev/target-vue/toolchain"),
129
+ svelte: () => import("@unframework.dev/target-svelte/toolchain"),
130
+ solid: () => import("@unframework.dev/target-solid/toolchain"),
131
+ angular: () => import("@unframework.dev/target-angular/toolchain"),
132
+ qwik: () => import("@unframework.dev/target-qwik/toolchain"),
133
+ astro: () => import("@unframework.dev/target-astro/toolchain")
134
+ };
135
+ /**
136
+ * Loads a target's toolchain, refusing one of another name. It loads from this package, which
137
+ * depends on every target, so a project need not install the target packages itself: the
138
+ * preview (`@unframework.dev/visual`) builds its servers from it too.
139
+ */
140
+ async function loadToolchain(target) {
141
+ let module;
142
+ try {
143
+ module = await TOOLCHAINS[target]();
144
+ } catch (error) {
145
+ throw new Error(`[uf] The ${target} toolchain (@unframework.dev/target-${target}/toolchain) could not be loaded: install the ${target} framework and its Vite plugin.`, { cause: error });
146
+ }
147
+ const toolchain = module.toolchain ?? module.default;
148
+ if (!toolchain || toolchain.name !== target) throw new Error(`[uf] @unframework.dev/target-${target}/toolchain must export \`toolchain\` with name "${target}".`);
149
+ return toolchain;
150
+ }
151
+ async function unpluginOf(target) {
152
+ const { default: unframework } = await import("@unframework.dev/unplugin/vite");
153
+ return unframework({
154
+ target,
155
+ onCompile: (event) => recordCompiledModule(event)
156
+ });
157
+ }
158
+ function toolchainContext(setup, target) {
159
+ return {
160
+ toolchainDir: setup.toolchainDir(target),
161
+ root: setup.root
162
+ };
163
+ }
164
+ /**
165
+ * A project's `test` options: the defaults, then the toolchain's own, then the options this
166
+ * configuration owns. A toolchain that sets an owned option throws, as in the harness; setup files
167
+ * add up, this configuration's first.
168
+ */
169
+ function projectTest(target, fragment, defaults, owned) {
170
+ const toolchain = fragment ?? {};
171
+ const taken = Object.keys(toolchain).filter((key) => key !== "setupFiles" && key in owned);
172
+ if (taken.length) throw new Error(`[uf] The ${target} toolchain's Vite configuration sets ${taken.map((key) => `test.${key}`).join(", ")}, which defineTestConfig owns.`);
173
+ const setupFiles = [owned.setupFiles ?? [], toolchain.setupFiles ?? []].flat();
174
+ return {
175
+ ...defaults,
176
+ ...toolchain,
177
+ ...owned,
178
+ ...setupFiles.length ? { setupFiles } : {}
179
+ };
180
+ }
181
+ function resolveModule(specifier) {
182
+ return fileURLToPath(import.meta.resolve(specifier));
183
+ }
184
+ /**
185
+ * The file of a toolchain's browser mount adapter (`toolchain.client`), resolved from this
186
+ * package, which depends on the target: a Vite server outside the test projects imports it by
187
+ * path, since the project need not install the target package (pnpm keeps it out of reach).
188
+ */
189
+ function toolchainClientFile(toolchain) {
190
+ return resolveModule(toolchain.client);
191
+ }
192
+ async function browserProject(setup, target) {
193
+ const name = `browser:${target}`;
194
+ const toolchain = await loadToolchain(target);
195
+ const context = toolchainContext(setup, target);
196
+ const fragment = await toolchain.vite("browser", context);
197
+ return {
198
+ ...mergeConfig({
199
+ root: setup.root,
200
+ plugins: [...await unpluginOf(target), noErrorBroadcast()],
201
+ optimizeDeps: {
202
+ include: ["@unframework.dev/testing > axe-core", "@unframework.dev/testing > parse5"],
203
+ exclude: ["@unframework.dev/testing", "@unframework.dev/target-qwik"]
204
+ }
205
+ }, fragment),
206
+ extends: false,
207
+ test: projectTest(target, fragment.test, {
208
+ testTimeout: TEST_TIMEOUT,
209
+ expect: {
210
+ poll: { timeout: 5e3 },
211
+ requireAssertions: true
212
+ }
213
+ }, {
214
+ name,
215
+ root: setup.root,
216
+ include: setup.cases.map((info) => info.spec),
217
+ exclude: [...EXCLUDED],
218
+ setupFiles: [resolveModule("@unframework.dev/testing/setup"), resolveModule(`@unframework.dev/testing/${target}`)],
219
+ provide: {
220
+ target,
221
+ ufHarness: setup.harness,
222
+ ufCapabilities: builtinTargets[target].capabilities,
223
+ ufNoOutput: {}
224
+ },
225
+ sequence: { groupOrder: group(setup, "browser", target) },
226
+ browser: {
227
+ ...parityBrowser({
228
+ name,
229
+ commands: {
230
+ ...toolchain.browserCommands?.(context),
231
+ ufMapStack
232
+ }
233
+ }),
234
+ screenshotDirectory: join(setup.root, ".reports", "failures")
235
+ }
236
+ })
237
+ };
238
+ }
239
+ async function ssrProject(setup, target) {
240
+ const toolchain = await loadToolchain(target);
241
+ const fragment = await toolchain.vite("ssr", toolchainContext(setup, target));
242
+ const config = mergeConfig({
243
+ root: setup.root,
244
+ plugins: await unpluginOf(target)
245
+ }, fragment);
246
+ const cases = setup.cases.map((info) => ({
247
+ id: info.id,
248
+ dir: info.dir,
249
+ source: info.source
250
+ }));
251
+ return {
252
+ ...config,
253
+ extends: false,
254
+ test: projectTest(target, fragment.test, {
255
+ environment: "node",
256
+ pool: "forks",
257
+ testTimeout: TEST_TIMEOUT
258
+ }, {
259
+ name: `ssr:${target}`,
260
+ root: setup.root,
261
+ include: [resolveModule("@unframework.dev/testing/ssr/spec")],
262
+ exclude: [],
263
+ server: { deps: { inline: [TESTING_PACKAGE, TARGET_PACKAGES] } },
264
+ provide: {
265
+ target,
266
+ ufHarness: setup.harness,
267
+ ufServer: toolchain.server,
268
+ ufSsrCases: cases
269
+ },
270
+ sequence: { groupOrder: group(setup, "ssr", target) }
271
+ })
272
+ };
273
+ }
274
+ //#endregion
275
+ export { DEFAULT_INCLUDE, TARGET_PACKAGES, TESTING_PACKAGE, defineTestConfig, discoverCases, loadToolchain, runTargets, selectedTargets, toolchainClientFile, toolchainDirOf };
package/dist/diff.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ //#region src/diff.d.ts
2
+ /** Options for {@link diffLines}. */
3
+ export interface DiffOptions {
4
+ /** Unchanged lines shown around each change. */
5
+ context?: number;
6
+ /** The most diff lines printed before the rest is summarised. */
7
+ maxLines?: number;
8
+ }
9
+ /**
10
+ * A unified-style diff from `expected` to `actual`: `-` lines are expected, `+` lines are
11
+ * actual. Returns an empty string when the texts are equal.
12
+ */
13
+ export declare function diffLines(expected: string, actual: string, options?: DiffOptions): string;
14
+ //#endregion
package/dist/diff.js ADDED
@@ -0,0 +1,92 @@
1
+ //#region src/diff.ts
2
+ /** Above this many cells the LCS table is too large; the diff falls back to the first change. */
3
+ const MAX_CELLS = 4e6;
4
+ /**
5
+ * A unified-style diff from `expected` to `actual`: `-` lines are expected, `+` lines are
6
+ * actual. Returns an empty string when the texts are equal.
7
+ */
8
+ function diffLines(expected, actual, options = {}) {
9
+ if (expected === actual) return "";
10
+ const context = options.context ?? 3;
11
+ const maxLines = options.maxLines ?? 80;
12
+ const a = expected.split("\n");
13
+ const b = actual.split("\n");
14
+ const ops = a.length * b.length > MAX_CELLS ? firstChange(a, b) : lcsOps(a, b);
15
+ const lines = [];
16
+ let lastPrinted = -1;
17
+ const changed = ops.map((op) => op.kind !== " ");
18
+ for (let index = 0; index < ops.length; index += 1) {
19
+ if (!changed.slice(Math.max(0, index - context), index + context + 1).some((isChange) => isChange)) continue;
20
+ if (lastPrinted !== -1 && index > lastPrinted + 1) lines.push(" …");
21
+ const op = ops[index];
22
+ lines.push(`${op.kind} ${visible(op.text)}`);
23
+ lastPrinted = index;
24
+ }
25
+ return [
26
+ "- expected",
27
+ "+ actual",
28
+ ...lines.length > maxLines ? [...lines.slice(0, maxLines), ` … ${lines.length - maxLines} more diff line(s)`] : lines
29
+ ].join("\n");
30
+ }
31
+ function lcsOps(a, b) {
32
+ const width = b.length + 1;
33
+ const table = new Uint32Array((a.length + 1) * width);
34
+ for (let i = a.length - 1; i >= 0; i -= 1) for (let j = b.length - 1; j >= 0; j -= 1) table[i * width + j] = a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
35
+ const ops = [];
36
+ let i = 0;
37
+ let j = 0;
38
+ while (i < a.length && j < b.length) if (a[i] === b[j]) {
39
+ ops.push({
40
+ kind: " ",
41
+ text: a[i]
42
+ });
43
+ i += 1;
44
+ j += 1;
45
+ } else if (table[(i + 1) * width + j] >= table[i * width + j + 1]) {
46
+ ops.push({
47
+ kind: "-",
48
+ text: a[i]
49
+ });
50
+ i += 1;
51
+ } else {
52
+ ops.push({
53
+ kind: "+",
54
+ text: b[j]
55
+ });
56
+ j += 1;
57
+ }
58
+ while (i < a.length) ops.push({
59
+ kind: "-",
60
+ text: a[i++]
61
+ });
62
+ while (j < b.length) ops.push({
63
+ kind: "+",
64
+ text: b[j++]
65
+ });
66
+ return ops;
67
+ }
68
+ /** For very large inputs: everything up to the first differing line is shared, the rest differs. */
69
+ function firstChange(a, b) {
70
+ let start = 0;
71
+ while (start < a.length && start < b.length && a[start] === b[start]) start += 1;
72
+ return [
73
+ ...a.slice(0, start).map((text) => ({
74
+ kind: " ",
75
+ text
76
+ })),
77
+ ...a.slice(start).map((text) => ({
78
+ kind: "-",
79
+ text
80
+ })),
81
+ ...b.slice(start).map((text) => ({
82
+ kind: "+",
83
+ text
84
+ }))
85
+ ];
86
+ }
87
+ /** Makes trailing whitespace and carriage returns visible, since they are often the difference. */
88
+ function visible(text) {
89
+ return text.replace(/\r/g, "\\r").replace(/[ \t]+$/, (spaces) => spaces.replace(/ /g, "·"));
90
+ }
91
+ //#endregion
92
+ export { diffLines };
@@ -0,0 +1,236 @@
1
+ import { attributeName, childrenOf, isElement as isElement$1, isText as isText$1, parseHtml } from "../normalize/tree.js";
2
+ import { recordComputedLayout } from "../normalize/display.js";
3
+ import { checkOptions, normalizeTree } from "../normalize/pipeline.js";
4
+ //#region src/dom/serialize.ts
5
+ const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
6
+ const XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
7
+ /** Namespace names for messages. */
8
+ const NAMESPACES = {
9
+ [HTML_NAMESPACE]: "HTML",
10
+ "http://www.w3.org/2000/svg": "SVG",
11
+ "http://www.w3.org/1998/Math/MathML": "MathML"
12
+ };
13
+ const words = (list) => new Set(list.split(" "));
14
+ /** Elements that have no end tag. */
15
+ const VOID_ELEMENTS = words("area base basefont bgsound br col embed frame hr img input keygen link meta param source track wbr");
16
+ /** Elements whose text the HTML parser reads raw, so it is written unescaped. */
17
+ const RAW_TEXT_ELEMENTS = words("iframe noembed noframes noscript plaintext script style xmp");
18
+ /** Elements whose first line break the HTML parser drops, so one is written in its place. */
19
+ const LEADING_NEWLINE_ELEMENTS = words("listing pre textarea");
20
+ /** Input types whose `value` property is the user's state (the "value" value mode). */
21
+ const VALUE_MODE_TYPES = words("color date datetime-local email month number password range search tel text time url week");
22
+ const isElement = (node) => node.nodeType === 1;
23
+ const isText = (node) => node.nodeType === 3;
24
+ const isProcessingInstruction = (node) => node.nodeType === 7;
25
+ const isComment = (node) => node.nodeType === 8;
26
+ /** Whether `element` is the HTML element `<tag>`. */
27
+ function isHtml(element, tag) {
28
+ return element.namespaceURI === HTML_NAMESPACE && element.localName === tag;
29
+ }
30
+ /** Whether the element has a CSSOM `style` (HTML, SVG and MathML elements do). */
31
+ const hasStyle = (element) => "style" in element;
32
+ const escapeText = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
33
+ const escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
34
+ /**
35
+ * The form-control state an HTML element holds in properties, as `uf:*` pseudo-attributes:
36
+ * - `uf:value` on a `<textarea>` and on an `<input>` whose value is user state (text-like,
37
+ * number, date, color, range…), from the `value` property;
38
+ * - `uf:checked="true|false"` on checkboxes and radios, from `checked`;
39
+ * - `uf:indeterminate="true|false"` on checkboxes, from `indeterminate`;
40
+ * - `uf:selected="true|false"` on every `<option>`, from `selected`, which also covers a
41
+ * `<select>`'s value;
42
+ * - `uf:focused=""` on the element that has the focus (see `focusState`).
43
+ */
44
+ function formState(element) {
45
+ return [...controlState(element), ...focusState(element)];
46
+ }
47
+ /** The form-control state of `formState`, without the focus. */
48
+ function controlState(element) {
49
+ if (isHtml(element, "input")) {
50
+ if (element.type === "checkbox") return [["uf:checked", String(element.checked)], ["uf:indeterminate", String(element.indeterminate)]];
51
+ if (element.type === "radio") return [["uf:checked", String(element.checked)]];
52
+ return VALUE_MODE_TYPES.has(element.type) ? [["uf:value", element.value]] : [];
53
+ }
54
+ if (isHtml(element, "textarea")) return [["uf:value", element.value]];
55
+ if (isHtml(element, "option")) return [["uf:selected", String(element.selected)]];
56
+ return [];
57
+ }
58
+ /**
59
+ * `uf:focused=""` on the element that has the focus (`document.activeElement`), whatever its
60
+ * namespace: an interaction that moves the focus, or loses it, shows in the DOM L7 and L9
61
+ * compare. Playwright's ARIA snapshot marks it only in its AI mode, whose output differs by
62
+ * target (ADR-0050). It is read whether the page has the focus or not (`hasFocus()` depends on
63
+ * the frame's), and never on the body, which holds the focus when nothing else does.
64
+ */
65
+ function focusState(element) {
66
+ const document = element.ownerDocument;
67
+ return element === document.activeElement && element !== document.body ? [["uf:focused", ""]] : [];
68
+ }
69
+ /**
70
+ * The element's attributes as they apply now. A `style` attribute is written as the CSSOM
71
+ * serialises its declarations (`style.cssText`), so a style set through the CSSOM (React's
72
+ * `el.style.margin = "0"`, which reads back as `margin: 0px;`) and the same style set as an
73
+ * attribute (`margin:0`) compare equal.
74
+ */
75
+ function attributesOf(element) {
76
+ return Array.from(element.attributes, (attribute) => [attribute.name, attribute.name === "style" && hasStyle(element) ? element.style.cssText : attribute.value]);
77
+ }
78
+ /** The node holding an element's children: a `<template>`'s content, or the element. */
79
+ function holderOf(element) {
80
+ return isHtml(element, "template") ? element.content : element;
81
+ }
82
+ function serializeChildren(element) {
83
+ const rawText = element.namespaceURI === HTML_NAMESPACE && RAW_TEXT_ELEMENTS.has(element.localName);
84
+ let html = "";
85
+ for (const child of holderOf(element).childNodes) if (isElement(child)) html += serializeElement(child);
86
+ else if (isText(child)) html += rawText ? child.data : escapeText(child.data);
87
+ else if (isComment(child)) html += `<!--${child.data}-->`;
88
+ else if (isProcessingInstruction(child)) html += `<?${child.target} ${child.data}>`;
89
+ return html;
90
+ }
91
+ function serializeElement(element) {
92
+ const html = element.namespaceURI === HTML_NAMESPACE;
93
+ const tag = element.localName;
94
+ const start = `<${tag}${[...attributesOf(element), ...html ? formState(element) : focusState(element)].map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("")}>`;
95
+ if (html && VOID_ELEMENTS.has(tag)) return start;
96
+ const content = serializeChildren(element);
97
+ return `${start}${html && LEADING_NEWLINE_ELEMENTS.has(tag) && content.startsWith("\n") ? "\n" : ""}${content}</${tag}>`;
98
+ }
99
+ /**
100
+ * Serialises the children of `root` (not `root` itself) to HTML, as `innerHTML` does, with two
101
+ * differences that make the live state comparable:
102
+ *
103
+ * - form-control state is added as `uf:value`, `uf:checked`, `uf:indeterminate` and
104
+ * `uf:selected` pseudo-attributes, read from properties (see `formState`), and the element
105
+ * that has the focus is marked `uf:focused` (see `focusState`);
106
+ * - `style` attributes are written as the CSSOM serialises them (see `attributesOf`).
107
+ *
108
+ * The result parses back into the same tree: a `<pre>`, `<textarea>` or `<listing>` whose text
109
+ * starts with a line break gets the extra one the parser drops. Shadow roots are not included.
110
+ */
111
+ function serializeDom(root) {
112
+ return serializeChildren(root);
113
+ }
114
+ /**
115
+ * {@link normalizeDom}, with the renaming of the generated ids it found, from each original id
116
+ * to its `uf-id-N`: a trace renames the ids a step's emitted payloads carry with it.
117
+ */
118
+ function normalizeDomWithIds(root, options = {}) {
119
+ checkOptions(options);
120
+ const parsed = parseHtml(serializeDom(root));
121
+ const mismatch = compareTrees(holderOf(root), parsed, "");
122
+ if (mismatch) throw new Error(`normalizeDom: the live DOM has a structure HTML cannot express, so the HTML parser would rebuild it differently: ${mismatch}`);
123
+ const ids = /* @__PURE__ */ new Map();
124
+ return {
125
+ html: normalizeTree(parsed, options, ids),
126
+ ids
127
+ };
128
+ }
129
+ /**
130
+ * The children of a node as items: elements, runs of text (adjacent text nodes read back as
131
+ * one, and empty text is not written), and the rest (comments, processing instructions).
132
+ */
133
+ function itemsOf(children, kind) {
134
+ const items = [];
135
+ for (const child of children) {
136
+ const item = kind(child);
137
+ const last = items.at(-1);
138
+ if ("text" in item && last && "text" in last) last.text += item.text;
139
+ else items.push(item);
140
+ }
141
+ return items.filter((item) => !("text" in item) || item.text !== "");
142
+ }
143
+ /**
144
+ * Walks the live children of `live` and the parsed children of `parsed` side by side, and
145
+ * describes the first difference: an element whose namespace, name, attribute names or
146
+ * attribute values differ, or that only one tree has, and text that reads back changed.
147
+ */
148
+ function compareTrees(live, parsed, path) {
149
+ const liveItems = itemsOf(live.childNodes, (node) => {
150
+ if (isElement(node)) return { element: node };
151
+ if (isText(node)) return { text: node.data };
152
+ return { other: node.nodeName };
153
+ });
154
+ const parsedItems = itemsOf(childrenOf(parsed), (node) => {
155
+ if (isElement$1(node)) return { element: node };
156
+ if (isText$1(node)) return { text: node.value };
157
+ return { other: node.nodeName };
158
+ });
159
+ const where = path || "the root";
160
+ for (let index = 0; index < Math.max(liveItems.length, parsedItems.length); index++) {
161
+ const item = liveItems[index];
162
+ const rebuilt = parsedItems[index];
163
+ if (!item) return `the parser inserts ${describeItem(rebuilt)} at ${where}.`;
164
+ if (!rebuilt) return `the live ${describeItem(item)} at ${where} has no counterpart.`;
165
+ if ("element" in item !== "element" in rebuilt) return `the live ${describeItem(item)} at ${where} parses as ${describeItem(rebuilt)}.`;
166
+ if ("text" in item && "text" in rebuilt && item.text !== rebuilt.text) return `the text ${JSON.stringify(item.text)} at ${where} reads back as ${JSON.stringify(rebuilt.text)}.`;
167
+ if (!("element" in item) || !("element" in rebuilt)) continue;
168
+ const element = item.element;
169
+ const here = `${path}${path ? " > " : ""}${element.localName}`;
170
+ const mismatch = compareElements(element, rebuilt.element, here) ?? compareTrees(holderOf(element), rebuilt.element, here);
171
+ if (mismatch) return mismatch;
172
+ recordLayout(element, rebuilt.element);
173
+ }
174
+ }
175
+ /**
176
+ * Records the computed values the normaliser reads in place of the inline style (see
177
+ * `ComputedLayout`) under the element's rebuild. An element in a `<template>`'s inert content
178
+ * has no window and no computed style: it keeps the static reading.
179
+ */
180
+ function recordLayout(element, rebuilt) {
181
+ const view = element.ownerDocument.defaultView;
182
+ if (!view || !element.isConnected) return;
183
+ const computed = view.getComputedStyle(element);
184
+ recordComputedLayout(rebuilt, {
185
+ display: computed.display,
186
+ position: computed.position,
187
+ float: computed.float,
188
+ unicodeBidi: computed.unicodeBidi,
189
+ whiteSpaceCollapse: computed.whiteSpaceCollapse
190
+ });
191
+ }
192
+ /** Describes the namespace, name and attributes in which a live element and its rebuild differ. */
193
+ function compareElements(element, rebuilt, here) {
194
+ if (element.namespaceURI !== rebuilt.namespaceURI || element.localName !== rebuilt.tagName) return `the live ${describe(element.namespaceURI, element.localName)} at ${here} parses as ${describe(rebuilt.namespaceURI, rebuilt.tagName)}.`;
195
+ const pseudo = new Set((element.namespaceURI === HTML_NAMESPACE ? formState(element) : focusState(element)).map(([name]) => name));
196
+ const liveValues = new Map(Array.from(element.attributes, (attribute) => [liveAttributeKey(attribute), attribute.name === "style" && hasStyle(element) ? element.style.cssText : attribute.value]));
197
+ const parsedValues = new Map(rebuilt.attrs.filter((attribute) => !pseudo.has(attributeName(attribute))).map((attribute) => [parsedAttributeKey(attribute), attribute.value]));
198
+ const liveNames = [...liveValues.keys()].toSorted();
199
+ const parsedNames = [...parsedValues.keys()].toSorted();
200
+ if (liveNames.join("\n") !== parsedNames.join("\n")) return `the attributes of ${here} are [${liveNames.join(", ")}] live and [${parsedNames.join(", ")}] once parsed.`;
201
+ for (const name of liveNames) {
202
+ const value = liveValues.get(name);
203
+ const read = parsedValues.get(name);
204
+ if (value !== read) return `the ${name} of ${here} is ${JSON.stringify(value)} live and reads back as ${JSON.stringify(read)}.`;
205
+ }
206
+ }
207
+ /** A live or parsed item for a message: an element, text, or a comment. */
208
+ function describeItem(item) {
209
+ if ("text" in item) return `text ${JSON.stringify(item.text)}`;
210
+ if ("other" in item) return item.other;
211
+ const element = item.element;
212
+ return "localName" in element ? describe(element.namespaceURI, element.localName) : describe(element.namespaceURI, element.tagName);
213
+ }
214
+ /** An element for a message: `<circle>` in HTML, `SVG <circle>`. */
215
+ function describe(namespace, name) {
216
+ const label = NAMESPACES[namespace ?? ""] ?? namespace ?? "no namespace";
217
+ return label === "HTML" ? `<${name}>` : `${label} <${name}>`;
218
+ }
219
+ /**
220
+ * A live attribute's identity: its namespace and local name. A namespace declaration (`xmlns`,
221
+ * `xmlns:xlink`) is inert in an HTML document, and frameworks set it without its namespace
222
+ * (Vue's and React's `setAttribute("xmlns", …)`), so it is known by its qualified name alone.
223
+ */
224
+ function liveAttributeKey(attribute) {
225
+ return attribute.namespaceURI === XMLNS_NAMESPACE || attribute.namespaceURI === null && /^xmlns(?::|$)/.test(attribute.name) ? attribute.name : qualified(attribute.namespaceURI, attribute.localName);
226
+ }
227
+ /** A parsed attribute's identity, as `liveAttributeKey` gives it. */
228
+ function parsedAttributeKey(attribute) {
229
+ return attribute.namespace === XMLNS_NAMESPACE ? attributeName(attribute) : qualified(attribute.namespace, attribute.name);
230
+ }
231
+ /** An attribute's namespace and local name, which together identify it. */
232
+ function qualified(namespace, name) {
233
+ return namespace ? `{${namespace}}${name}` : name;
234
+ }
235
+ //#endregion
236
+ export { normalizeDomWithIds, serializeDom };
@@ -0,0 +1,13 @@
1
+ //#region src/errors.d.ts
2
+ /**
3
+ * The text of a thrown value, for a layer's failure message. Assertion errors on strings get a
4
+ * line diff, because the message is all the parity matrix and the combined error keep.
5
+ */
6
+ export declare function formatError(error: unknown): string;
7
+ /**
8
+ * A thrown or serialised error's message, then each of its causes' messages, outermost first.
9
+ * Vitest wraps an error it cannot attribute to a test (a failed import, a closed browser
10
+ * connection) in its own, so the cause is the part that says what happened.
11
+ */
12
+ export declare function errorMessages(error: unknown): string[];
13
+ //#endregion
package/dist/errors.js ADDED
@@ -0,0 +1,38 @@
1
+ import { diffLines } from "./diff.js";
2
+ //#region src/errors.ts
3
+ /**
4
+ * The text of a thrown value, for a layer's failure message. Assertion errors on strings get a
5
+ * line diff, because the message is all the parity matrix and the combined error keep.
6
+ */
7
+ function formatError(error) {
8
+ if (!(error instanceof Error)) return String(error);
9
+ const assertion = error;
10
+ if (assertion.showDiff && typeof assertion.actual === "string" && typeof assertion.expected === "string" && assertion.actual.includes("\n")) return `${error.message}\n${diffLines(assertion.expected, assertion.actual)}`;
11
+ return error.message;
12
+ }
13
+ /**
14
+ * A thrown or serialised error's message, then each of its causes' messages, outermost first.
15
+ * Vitest wraps an error it cannot attribute to a test (a failed import, a closed browser
16
+ * connection) in its own, so the cause is the part that says what happened.
17
+ */
18
+ function errorMessages(error) {
19
+ if (typeof error !== "object" || error === null) return [String(error)];
20
+ const messages = [messageOf(error)];
21
+ const seen = /* @__PURE__ */ new Set([error]);
22
+ const first = "cause" in error ? error.cause : void 0;
23
+ for (let cause = first; hasMessage(cause) && !seen.has(cause); cause = cause.cause) {
24
+ seen.add(cause);
25
+ messages.push(messageOf(cause));
26
+ }
27
+ return messages;
28
+ }
29
+ function hasMessage(value) {
30
+ return typeof value === "object" && value !== null && "message" in value;
31
+ }
32
+ /** A message as Vitest serialises it, or what `load-failures` has always said for none. */
33
+ function messageOf(error) {
34
+ const message = "message" in error ? error.message : void 0;
35
+ return typeof message === "string" ? message : "an error without a message";
36
+ }
37
+ //#endregion
38
+ export { errorMessages, formatError };