@locusqa/runner 0.1.0 → 0.1.1

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.
package/bin/locus-runner CHANGED
@@ -2,9 +2,27 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { realpathSync, writeFileSync } from "node:fs";
5
+ import { cpus, freemem } from "node:os";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { parseArgs } from "node:util";
7
8
 
9
+ // src/concurrency.ts
10
+ var BYTES_PER_SLOT = 1024 * 1024 * 1024;
11
+ var HARD_SLOT_CAP = 4;
12
+ function resolveConcurrency(requested, cpuCount, freeMemoryBytes) {
13
+ const wanted = Number.isFinite(requested) && requested >= 1 ? Math.floor(requested) : 1;
14
+ const byCpu = Math.floor(cpuCount / 2);
15
+ const byMemory = Math.floor(freeMemoryBytes / BYTES_PER_SLOT);
16
+ const limit = Math.max(1, Math.min(HARD_SLOT_CAP, byCpu, byMemory));
17
+ if (wanted <= limit) {
18
+ return { value: wanted, warning: void 0 };
19
+ }
20
+ return {
21
+ value: limit,
22
+ warning: `--concurrency ${wanted} is too many for this machine (${cpuCount} CPU cores, ${(freeMemoryBytes / BYTES_PER_SLOT).toFixed(1)} GiB free memory); using ${limit}.`
23
+ };
24
+ }
25
+
8
26
  // src/engine-bundle.ts
9
27
  function loadEngineBundle() {
10
28
  return '"use strict";\nvar LocusEngine = (() => {\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n };\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === "object" || typeof from === "function") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);\n\n // src/index.ts\n var src_exports = {};\n __export(src_exports, {\n UnsupportedSelectorError: () => UnsupportedSelectorError,\n accessibleName: () => accessibleName,\n buildLocatorSet: () => buildLocatorSet,\n captureVerification: () => captureVerification,\n captureVerificationForReplay: () => captureVerificationForReplay,\n elementText: () => elementText,\n idVolatility: () => idVolatility,\n implicitRole: () => implicitRole,\n isHidden: () => isHidden,\n isTrustworthyName: () => isTrustworthyName,\n normalizeSpace: () => normalizeSpace,\n readIdentifier: () => readIdentifier,\n readNeighbour: () => readNeighbour,\n resolve: () => resolve,\n sha256Hex: () => sha256Hex,\n splitChain: () => splitChain,\n storageCaptureTools: () => storageCaptureTools,\n strategyFamily: () => strategyFamily,\n textVolatility: () => textVolatility,\n valueVolatility: () => valueVolatility\n });\n\n // src/accessibility.ts\n var LANDMARK_AND_TAG_ROLES = {\n a: "link",\n article: "article",\n aside: "complementary",\n button: "button",\n dialog: "dialog",\n form: "form",\n h1: "heading",\n h2: "heading",\n h3: "heading",\n h4: "heading",\n h5: "heading",\n h6: "heading",\n li: "listitem",\n main: "main",\n nav: "navigation",\n ol: "list",\n option: "option",\n progress: "progressbar",\n table: "table",\n tbody: "rowgroup",\n td: "cell",\n textarea: "textbox",\n th: "columnheader",\n tr: "row",\n ul: "list"\n };\n var BUTTON_INPUT_TYPES = /* @__PURE__ */ new Set(["button", "submit", "reset", "image"]);\n var TEXTBOX_INPUT_TYPES = /* @__PURE__ */ new Set(["", "text", "email", "tel", "url", "password"]);\n function normalizeSpace(text) {\n return text.replace(/\\s+/g, " ").trim();\n }\n function implicitRole(el) {\n const explicit = el.getAttribute("role");\n if (explicit !== null) {\n const first = explicit.trim().split(/\\s+/)[0];\n if (first) return first;\n }\n const tag = el.tagName.toLowerCase();\n if (tag === "a") return el.hasAttribute("href") ? "link" : null;\n if (tag === "img") return el.getAttribute("alt") === "" ? "presentation" : "img";\n if (tag === "select") {\n const size = Number(el.getAttribute("size") ?? "0");\n return el.hasAttribute("multiple") || size > 1 ? "listbox" : "combobox";\n }\n if (tag === "input") {\n const type = (el.getAttribute("type") ?? "").toLowerCase();\n if (BUTTON_INPUT_TYPES.has(type)) return "button";\n if (type === "checkbox") return "checkbox";\n if (type === "radio") return "radio";\n if (type === "range") return "slider";\n if (type === "number") return "spinbutton";\n if (type === "search") return el.hasAttribute("list") ? "combobox" : "searchbox";\n if (TEXTBOX_INPUT_TYPES.has(type)) return el.hasAttribute("list") ? "combobox" : "textbox";\n return null;\n }\n return LANDMARK_AND_TAG_ROLES[tag] ?? null;\n }\n var NAME_FROM_CONTENT_ROLES = /* @__PURE__ */ new Set([\n "button",\n "link",\n "heading",\n "cell",\n "columnheader",\n "listitem",\n "option",\n "tab",\n "menuitem",\n "checkbox",\n "radio"\n ]);\n function textOf(el) {\n const parts = [];\n function collect(node) {\n if (node.nodeType === 3) {\n const val = node.nodeValue?.trim();\n if (val) parts.push(val);\n return;\n }\n if (node.nodeType === 1) {\n const childEl = node;\n if (childEl.tagName.toLowerCase() === "svg" && !childEl.getAttribute("aria-label")) {\n return;\n }\n if (isHidden(childEl)) return;\n const childAria = childEl.getAttribute("aria-label");\n if (childAria && childAria.trim()) {\n parts.push(childAria.trim());\n return;\n }\n const childAlt = childEl.getAttribute("alt");\n if (childAlt && childAlt.trim()) {\n parts.push(childAlt.trim());\n return;\n }\n for (let child = childEl.firstChild; child; child = child.nextSibling) {\n collect(child);\n }\n }\n }\n for (let child = el.firstChild; child; child = child.nextSibling) {\n collect(child);\n }\n const result = parts.join(" ").replace(/\\s+/g, " ").trim();\n if (result) return result;\n return normalizeSpace(el.textContent ?? "");\n }\n function labelText(el) {\n const doc = el.ownerDocument;\n const parts = [];\n if (el.id) {\n for (const label of Array.from(doc.querySelectorAll("label"))) {\n if (label.getAttribute("for") === el.id) parts.push(textOf(label));\n }\n }\n const wrapping = el.closest("label");\n if (wrapping) parts.push(textOf(wrapping));\n const joined = normalizeSpace(parts.join(" "));\n return joined === "" ? null : joined;\n }\n function accessibleName(el) {\n const doc = el.ownerDocument;\n const labelledBy = el.getAttribute("aria-labelledby");\n if (labelledBy) {\n const text = normalizeSpace(\n labelledBy.split(/\\s+/).map((id) => doc.getElementById(id)?.textContent ?? "").join(" ")\n );\n if (text) return { name: text, source: "aria-labelledby" };\n }\n const ariaLabel = el.getAttribute("aria-label");\n if (ariaLabel && ariaLabel.trim())\n return { name: normalizeSpace(ariaLabel), source: "aria-label" };\n const tag = el.tagName.toLowerCase();\n const type = (el.getAttribute("type") ?? "").toLowerCase();\n if (tag === "img") {\n const alt = el.getAttribute("alt");\n if (alt && alt.trim()) return { name: normalizeSpace(alt), source: "alt" };\n }\n if (tag === "input" && BUTTON_INPUT_TYPES.has(type)) {\n const value = el.getAttribute("value");\n if (value && value.trim()) return { name: normalizeSpace(value), source: "value" };\n if (type === "submit") return { name: "Submit", source: "value" };\n if (type === "reset") return { name: "Reset", source: "value" };\n }\n if (tag === "input" || tag === "select" || tag === "textarea") {\n const label = labelText(el);\n if (label) return { name: label, source: "label" };\n const placeholder = el.getAttribute("placeholder");\n if (placeholder && placeholder.trim())\n return { name: normalizeSpace(placeholder), source: "placeholder" };\n }\n const role = implicitRole(el);\n if (role !== null && NAME_FROM_CONTENT_ROLES.has(role) && tag !== "input") {\n const text = textOf(el);\n if (text) return { name: text, source: "content" };\n }\n const title = el.getAttribute("title");\n if (title && title.trim()) return { name: normalizeSpace(title), source: "title" };\n return null;\n }\n function isHidden(el) {\n const view = el.ownerDocument.defaultView;\n for (let node = el; node; node = node.parentElement) {\n if (node.hasAttribute("hidden") || node.getAttribute("aria-hidden") === "true") return true;\n if (view) {\n const style = view.getComputedStyle(node);\n if (style.display === "none" || style.visibility === "hidden") return true;\n }\n }\n return false;\n }\n\n // src/resolve.ts\n var UnsupportedSelectorError = class extends Error {\n constructor(expression, reason) {\n super(`unsupported selector ${JSON.stringify(expression)}: ${reason}`);\n this.name = "UnsupportedSelectorError";\n }\n };\n function splitChain(expression) {\n const parts = [];\n let depth = 0;\n let quote = null;\n let start = 0;\n for (let i = 0; i < expression.length; i++) {\n const ch = expression.charAt(i);\n if (quote !== null) {\n if (ch === "\\\\") i++;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === \'"\' || ch === "\'") quote = ch;\n else if (ch === "[" || ch === "(") depth++;\n else if (ch === "]" || ch === ")") depth--;\n else if (depth === 0 && expression.startsWith(">>", i)) {\n parts.push(expression.slice(start, i).trim());\n start = i + 2;\n i++;\n }\n }\n parts.push(expression.slice(start).trim());\n if (parts.some((p) => p === ""))\n throw new UnsupportedSelectorError(expression, "empty chain segment");\n return parts;\n }\n function readQuoted(source, from, expression) {\n const quote = source.charAt(from);\n if (quote !== \'"\' && quote !== "\'")\n throw new UnsupportedSelectorError(expression, "expected a quoted value");\n let value = "";\n for (let i = from + 1; i < source.length; i++) {\n const ch = source.charAt(i);\n if (ch === "\\\\") {\n value += source.charAt(i + 1);\n i++;\n } else if (ch === quote) {\n return { value, next: i + 1 };\n } else {\n value += ch;\n }\n }\n throw new UnsupportedSelectorError(expression, "unterminated quoted value");\n }\n function parseRole(part) {\n const match = /^role=([a-zA-Z]+)/.exec(part);\n if (!match || match[1] === void 0)\n throw new UnsupportedSelectorError(part, "malformed role selector");\n const query = { role: match[1].toLowerCase(), name: null };\n let i = match[0].length;\n while (i < part.length) {\n if (part.charAt(i) !== "[") throw new UnsupportedSelectorError(part, "expected [");\n const eq = part.indexOf("=", i);\n if (eq < 0) throw new UnsupportedSelectorError(part, "expected =");\n const key = part.slice(i + 1, eq).trim();\n if (key !== "name")\n throw new UnsupportedSelectorError(part, `unsupported role attribute ${key}`);\n const quoted = readQuoted(part, eq + 1, part);\n i = quoted.next;\n let exact = false;\n const flag = part.charAt(i);\n if (flag === "s") {\n exact = true;\n i++;\n } else if (flag === "i") {\n i++;\n }\n if (part.charAt(i) !== "]") throw new UnsupportedSelectorError(part, "expected ]");\n i++;\n query.name = { value: quoted.value, exact };\n }\n return query;\n }\n function nameMatches(actual, wanted) {\n const normalized = normalizeSpace(wanted.value);\n if (wanted.exact) return actual === normalized;\n return actual.toLowerCase() === normalized.toLowerCase();\n }\n function queryRole(scope, query) {\n const out = [];\n for (const el of Array.from(scope.querySelectorAll("*"))) {\n if (implicitRole(el) !== query.role) continue;\n if (isHidden(el)) continue;\n if (query.name !== null) {\n const name = accessibleName(el);\n if (name === null || !nameMatches(name.name, query.name)) continue;\n }\n out.push(el);\n }\n return out;\n }\n var TEXT_IS = /^([a-zA-Z][a-zA-Z0-9-]*)?:text-is\\(/;\n var SKIPPED_TEXT_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "NOSCRIPT", "STYLE"]);\n function elementText(el) {\n if (SKIPPED_TEXT_TAGS.has(el.tagName)) return "";\n let out = "";\n for (let child = el.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 3) out += child.nodeValue ?? "";\n else if (child.nodeType === 1) out += elementText(child);\n }\n return normalizeSpace(out.replace(/\\u200b/g, ""));\n }\n function parseTextIs(part) {\n const match = TEXT_IS.exec(part);\n if (!match) throw new UnsupportedSelectorError(part, "malformed text selector");\n const quoted = readQuoted(part, match[0].length, part);\n if (part.slice(quoted.next) !== ")") throw new UnsupportedSelectorError(part, "expected )");\n return { tag: match[1] ?? "*", text: normalizeSpace(quoted.value) };\n }\n function queryTextIs(scope, part) {\n const query = parseTextIs(part);\n const out = [];\n for (const el of Array.from(scope.querySelectorAll(query.tag))) {\n if (elementText(el) !== query.text) continue;\n if (Array.from(el.children).some((child) => elementText(child) === query.text)) continue;\n out.push(el);\n }\n return out;\n }\n function queryXPath(scope, xpath, doc) {\n const snapshot = doc.evaluate(xpath, scope, null, 7, null);\n const out = [];\n for (let i = 0; i < snapshot.snapshotLength; i++) {\n const node = snapshot.snapshotItem(i);\n if (node !== null && node.nodeType === 1) out.push(node);\n }\n return out;\n }\n function queryPart(scope, part, doc) {\n if (part.startsWith("role=")) return queryRole(scope, parseRole(part));\n if (part.startsWith("xpath=")) return queryXPath(scope, part.slice("xpath=".length), doc);\n if (TEXT_IS.test(part)) return queryTextIs(scope, part);\n if (part.startsWith("text=") || part.includes(":has-text(") || part.includes(":text(")) {\n throw new UnsupportedSelectorError(part, "text selectors are not supported");\n }\n return Array.from(scope.querySelectorAll(part));\n }\n var NTH_PART = /^nth=(.*)$/;\n function parseNth(part, raw) {\n if (!/^-?\\d+$/.test(raw.trim()))\n throw new UnsupportedSelectorError(part, "nth= needs a whole number");\n return Number.parseInt(raw.trim(), 10);\n }\n function pickNth(matches, index) {\n const at = index < 0 ? matches.length + index : index;\n const picked = matches[at];\n return picked === void 0 ? [] : [picked];\n }\n function resolve(expression, doc) {\n let scopes = [doc];\n for (const part of splitChain(expression)) {\n const nth = NTH_PART.exec(part);\n if (nth !== null) {\n if (scopes.length === 1 && scopes[0] === doc)\n throw new UnsupportedSelectorError(part, "nth= needs a selector before it");\n scopes = pickNth(scopes, parseNth(part, nth[1] ?? ""));\n if (scopes.length === 0) return [];\n continue;\n }\n const seen = /* @__PURE__ */ new Set();\n const next = [];\n for (const scope of scopes) {\n for (const el of queryPart(scope, part, doc)) {\n if (!seen.has(el)) {\n seen.add(el);\n next.push(el);\n }\n }\n }\n scopes = next;\n if (scopes.length === 0) return [];\n }\n return scopes;\n }\n\n // src/volatility.ts\n var UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;\n var LONG_HEX = /[0-9a-f]{8,}/i;\n var LONG_DIGITS = /\\d{5,}/;\n var GENERATED_PREFIX = /^(css|sc|jsx|emotion|styled|makeStyles|MuiBox)[-_]/i;\n var FRAMEWORK_ID = /^(:r[0-9a-z]*:|ember\\d+|ng-\\d+|react-select-\\d+|mui-\\d+|radix-|headlessui-|__next|rc_select_\\d+)/i;\n var COUNTER_ID = /^[a-z]+(?:[-_][a-z]+)*(?:[-_]\\d{1,4})+$/i;\n var GENERATED_ID = /^(\\u00ab.*\\u00bb|_r_[0-9a-z]+_|__BVID__\\d+|j_idt\\d+)$/i;\n function valueVolatility(value) {\n if (value.length > 60) return { volatile: true, reason: "value is unusually long" };\n if (UUID.test(value)) return { volatile: true, reason: "value contains a UUID" };\n if (FRAMEWORK_ID.test(value))\n return { volatile: true, reason: "value looks framework-generated" };\n if (GENERATED_PREFIX.test(value))\n return { volatile: true, reason: "value looks like a generated class" };\n if (LONG_HEX.test(value) && /\\d/.test(value))\n return { volatile: true, reason: "value contains a hash-like run" };\n if (LONG_DIGITS.test(value)) return { volatile: true, reason: "value contains a long number" };\n const digits = (value.match(/\\d/g) ?? []).length;\n if (value.length >= 6 && digits / value.length > 0.4)\n return { volatile: true, reason: "value is mostly digits" };\n return { volatile: false, reason: null };\n }\n function textVolatility(text) {\n if (text.length > 80) return { volatile: true, reason: "text is long" };\n if (/\\d{2,}/.test(text))\n return { volatile: true, reason: "text contains numbers that may change" };\n return { volatile: false, reason: null };\n }\n function idVolatility(id) {\n const value = valueVolatility(id);\n if (value.volatile) return value;\n if (GENERATED_ID.test(id)) return { volatile: true, reason: "id looks framework-generated" };\n if (COUNTER_ID.test(id))\n return { volatile: true, reason: "id looks like a render-order counter" };\n return { volatile: false, reason: null };\n }\n\n // src/generate.ts\n var TESTID_ATTRS = [\n "data-testid",\n "data-test-id",\n "data-test",\n "data-qa",\n "data-cy",\n "data-automation-id"\n ];\n var DESCRIPTIVE_ATTRS = ["aria-label", "placeholder", "alt", "title"];\n var RECORDED_ATTRS = [\n "id",\n "name",\n "type",\n "role",\n "href",\n "download",\n "for",\n "aria-label",\n "placeholder",\n "alt",\n "title",\n ...TESTID_ATTRS\n ];\n var CONTAINER_TAGS = /* @__PURE__ */ new Set([\n "form",\n "dialog",\n "table",\n "nav",\n "main",\n "aside",\n "fieldset",\n "section",\n "header",\n "footer",\n "ul",\n "ol",\n "tr"\n ]);\n var NAMED_CONTAINER_ROLES = /* @__PURE__ */ new Set([\n "form",\n "dialog",\n "navigation",\n "main",\n "complementary",\n "table",\n "region",\n "list"\n ]);\n var MAX_ANCESTORS_CHECKED = 6;\n var MAX_NAME_LENGTH = 100;\n var MAX_TEXT_LENGTH = 80;\n var STRATEGY_ORDER = ["semantic", "stable_attribute", "relational", "css", "xpath"];\n var INDEPENDENT_FAMILIES = /* @__PURE__ */ new Set(["semantic", "stable_attribute", "relational"]);\n var BASE_CONFIDENCE = {\n semantic: 0.85,\n stable_attribute: 0.8,\n relational: 0.7,\n css: 0.35,\n xpath: 0.25\n };\n var STABILITY_FACTOR = { stable: 1, moderate: 0.85, volatile: 0.6 };\n function esc(value) {\n return value.replace(/\\\\/g, "\\\\\\\\").replace(/"/g, \'\\\\"\');\n }\n function attrSelector(name, value) {\n return `[${name}="${esc(value)}"]`;\n }\n function tagOf(el) {\n return el.tagName.toLowerCase();\n }\n function measure(expression, target) {\n const matches = resolve(expression, target.ownerDocument);\n return { count: matches.length, unique: matches.length === 1 && matches[0] === target };\n }\n function ownText(el) {\n if (["input", "select", "textarea"].includes(tagOf(el))) return null;\n const text = textOf(el);\n return text !== "" && text.length <= MAX_TEXT_LENGTH ? text : null;\n }\n function recordedAttributes(el) {\n const out = {};\n for (const name of RECORDED_ATTRS) {\n const value = el.getAttribute(name);\n if (value !== null && value !== "") out[name] = value.slice(0, 200);\n }\n return out;\n }\n function confidenceOf(strategy, stability, unique, boost) {\n const base = boost ? 0.95 : BASE_CONFIDENCE[strategy];\n const value = base * STABILITY_FACTOR[stability] * (unique ? 1 : 0.4);\n return Math.round(Math.min(1, Math.max(0, value)) * 100) / 100;\n }\n function build(strategy, el, candidate, context) {\n const measured = measure(candidate.expression, el);\n const name = accessibleName(el);\n return {\n strategy,\n expression: candidate.expression,\n tag: tagOf(el),\n role: implicitRole(el),\n accessible_name: name === null ? null : name.name.slice(0, MAX_NAME_LENGTH),\n text: ownText(el),\n attributes: recordedAttributes(el),\n context,\n match_count: measured.count,\n unique: measured.unique,\n confidence: confidenceOf(strategy, candidate.stability, measured.unique, candidate.boost),\n stability: candidate.stability,\n evidence: candidate.evidence,\n fragility: candidate.fragility\n };\n }\n function semanticCandidate(el) {\n const role = implicitRole(el);\n const name = accessibleName(el);\n if (role === null || role === "presentation" || role === "generic" || name === null) return null;\n const text = name.name.slice(0, MAX_NAME_LENGTH);\n const textRisk = textVolatility(text);\n let stability = ["aria-label", "aria-labelledby", "label"].includes(name.source) ? "stable" : "moderate";\n const fragility = [];\n if (textRisk.volatile) {\n stability = "volatile";\n fragility.push(textRisk.reason ?? "name may change");\n }\n if (name.source === "content" || name.source === "placeholder" || name.source === "title") {\n fragility.push("depends on visible copy; breaks if the wording changes");\n }\n return {\n expression: `role=${role}[name="${esc(text)}"]`,\n stability,\n evidence: [`role ${role}`, `accessible name from ${name.source}`],\n fragility,\n boost: false\n };\n }\n function attributeCandidates(el, scopeTag) {\n const tag = scopeTag ? tagOf(el) : "";\n const out = [];\n for (const attr of TESTID_ATTRS) {\n const value = el.getAttribute(attr);\n if (value) {\n out.push({\n expression: `${tag}${attrSelector(attr, value)}`,\n stability: "stable",\n evidence: [`${attr} attribute`],\n fragility: [],\n boost: true\n });\n }\n }\n const id = el.getAttribute("id");\n if (id) {\n const risk = idVolatility(id);\n if (!risk.volatile) {\n out.push({\n expression: `${tag}${attrSelector("id", id)}`,\n stability: "stable",\n evidence: ["id attribute"],\n fragility: [],\n boost: false\n });\n }\n }\n const nameAttr = el.getAttribute("name");\n if (nameAttr && !valueVolatility(nameAttr).volatile) {\n out.push({\n expression: `${tag}${attrSelector("name", nameAttr)}`,\n stability: "moderate",\n evidence: ["name attribute"],\n fragility: [],\n boost: false\n });\n const type = el.getAttribute("type");\n if (type) {\n out.push({\n expression: `${tag}${attrSelector("name", nameAttr)}${attrSelector("type", type)}`,\n stability: "moderate",\n evidence: ["name and type attributes"],\n fragility: [],\n boost: false\n });\n }\n }\n for (const attr of DESCRIPTIVE_ATTRS) {\n const value = el.getAttribute(attr);\n if (value && value.length <= MAX_NAME_LENGTH && !textVolatility(value).volatile) {\n out.push({\n expression: `${tag}${attrSelector(attr, value)}`,\n stability: "moderate",\n evidence: [`${attr} attribute`],\n fragility: ["depends on copy; breaks if the wording changes"],\n boost: false\n });\n }\n }\n const href = el.getAttribute("href");\n if (tagOf(el) === "a" && href && !valueVolatility(href).volatile) {\n out.push({\n expression: `${tag}${attrSelector("href", href)}`,\n stability: "moderate",\n evidence: ["href attribute"],\n fragility: ["breaks if the route changes"],\n boost: false\n });\n }\n return out;\n }\n function pickBest(el, candidates) {\n for (const candidate of candidates) {\n if (measure(candidate.expression, el).unique) return candidate;\n }\n return candidates[0] ?? null;\n }\n function nthOfType(el) {\n let index = 1;\n for (let sibling = el.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {\n if (sibling.tagName === el.tagName) index++;\n }\n return index;\n }\n function sameTagSiblings(el) {\n const parent = el.parentElement;\n if (!parent) return 1;\n return Array.from(parent.children).filter((c) => c.tagName === el.tagName).length;\n }\n function anchorFor(ancestor) {\n for (const attr of TESTID_ATTRS) {\n const value = ancestor.getAttribute(attr);\n if (value)\n return {\n expression: `${tagOf(ancestor)}${attrSelector(attr, value)}`,\n evidence: `ancestor ${attr}`\n };\n }\n const id = ancestor.getAttribute("id");\n if (id && !idVolatility(id).volatile) {\n return { expression: `${tagOf(ancestor)}${attrSelector("id", id)}`, evidence: "ancestor id" };\n }\n const role = implicitRole(ancestor);\n const name = accessibleName(ancestor);\n if (role !== null && NAMED_CONTAINER_ROLES.has(role) && name !== null && !textVolatility(name.name).volatile) {\n return {\n expression: `role=${role}[name="${esc(name.name.slice(0, MAX_NAME_LENGTH))}"]`,\n evidence: `ancestor ${role} "${name.name}"`\n };\n }\n if (CONTAINER_TAGS.has(tagOf(ancestor)))\n return { expression: tagOf(ancestor), evidence: `ancestor <${tagOf(ancestor)}>` };\n return null;\n }\n function textCandidate(el) {\n if (["input", "select", "textarea"].includes(tagOf(el))) return null;\n const text = elementText(el);\n if (text === "" || text.length > MAX_NAME_LENGTH || textVolatility(text).volatile) return null;\n if (text !== textOf(el)) return null;\n return {\n expression: `${tagOf(el)}:text-is("${esc(text)}")`,\n stability: "moderate",\n evidence: ["exact visible text"],\n fragility: ["depends on visible copy; breaks if the wording changes"],\n boost: false\n };\n }\n function innerCandidates(el) {\n const out = [];\n const semantic = semanticCandidate(el);\n if (semantic) out.push(semantic);\n out.push(...attributeCandidates(el, true));\n const text = textCandidate(el);\n if (text) out.push(text);\n const tag = tagOf(el);\n const nth = sameTagSiblings(el) > 1 ? `:nth-of-type(${nthOfType(el)})` : "";\n out.push({\n expression: `${tag}${nth}`,\n stability: nth === "" ? "moderate" : "volatile",\n evidence: nth === "" ? ["tag within anchor"] : ["tag position within anchor"],\n fragility: nth === "" ? [] : ["position-dependent; breaks if siblings are added or reordered"],\n boost: false\n });\n return out;\n }\n function relationalCandidate(el) {\n let checked = 0;\n for (let ancestor = el.parentElement; ancestor && checked < MAX_ANCESTORS_CHECKED; ancestor = ancestor.parentElement) {\n if (ancestor === el.ownerDocument.body || ancestor === el.ownerDocument.documentElement) break;\n const anchor = anchorFor(ancestor);\n if (anchor === null) continue;\n checked++;\n for (const inner of innerCandidates(el)) {\n const expression = `${anchor.expression} >> ${inner.expression}`;\n const candidate = {\n expression,\n stability: inner.stability === "volatile" ? "volatile" : "moderate",\n evidence: [anchor.evidence, ...inner.evidence],\n fragility: inner.fragility,\n boost: false\n };\n if (measure(expression, el).unique) return { candidate, anchor: anchor.expression };\n }\n }\n return null;\n }\n function structuralCss(el) {\n const segments = [];\n let node = el;\n let anchored = false;\n while (node && node !== el.ownerDocument.documentElement) {\n const tag = tagOf(node);\n if (node !== el.ownerDocument.body) {\n const id = node.getAttribute("id");\n if (id && !idVolatility(id).volatile) {\n segments.unshift(`${tag}${attrSelector("id", id)}`);\n anchored = true;\n break;\n }\n if (node !== el && ["header", "main", "nav", "footer"].includes(tag) && node.ownerDocument.querySelectorAll(tag).length === 1) {\n segments.unshift(tag);\n anchored = true;\n break;\n }\n }\n if (node === el.ownerDocument.body) {\n segments.unshift("body");\n break;\n }\n segments.unshift(sameTagSiblings(node) > 1 ? `${tag}:nth-of-type(${nthOfType(node)})` : tag);\n node = node.parentElement;\n }\n return {\n expression: segments.join(" > "),\n stability: "volatile",\n evidence: [anchored ? "structural path from nearest anchor" : "structural path from body"],\n fragility: ["position-dependent; breaks if the layout changes"],\n boost: false\n };\n }\n function structuralXPath(el) {\n const segments = [];\n for (let node = el; node; node = node.parentElement) {\n const tag = tagOf(node);\n segments.unshift(sameTagSiblings(node) > 1 ? `${tag}[${nthOfType(node)}]` : tag);\n if (node === el.ownerDocument.documentElement) break;\n }\n return {\n expression: `xpath=/${segments.join("/")}`,\n stability: "volatile",\n evidence: ["absolute structural path"],\n fragility: ["position-dependent; breaks if the layout changes"],\n boost: false\n };\n }\n function ancestorContext(el) {\n const out = [];\n for (let node = el.parentElement; node && out.length < 3; node = node.parentElement) {\n if (node === el.ownerDocument.documentElement) break;\n out.push({ tag: tagOf(node), role: implicitRole(node) });\n }\n return out;\n }\n function isExplicitIdentifier(locator) {\n return locator.strategy === "stable_attribute" && locator.stability === "stable";\n }\n var REQUIRED_STRATEGIES = 3;\n var REQUIRED_STRATEGIES_WITH_ID = 2;\n function hasUniqueExplicitIdentifier(locators) {\n return locators.some((l) => l.unique && isExplicitIdentifier(l));\n }\n function isTrustworthyName(name, role, tag) {\n if (name === null) return false;\n const trimmed = name.trim();\n if (Array.from(trimmed).length < 3) return false;\n if (!/\\p{L}/u.test(trimmed)) return false;\n const lower = trimmed.toLowerCase();\n return lower !== (role ?? "").toLowerCase() && lower !== tag.toLowerCase();\n }\n function uniqueNamedSemantic(locators) {\n return locators.find(\n (l) => l.strategy === "semantic" && l.unique && l.stability !== "volatile" && l.role !== null && isTrustworthyName(l.accessible_name, l.role, l.tag)\n ) ?? null;\n }\n function hasUniqueNamedSemanticWithBackup(locators) {\n const semantic = uniqueNamedSemantic(locators);\n if (semantic === null || semantic.accessible_name === null) return false;\n const name = semantic.accessible_name.trim();\n return locators.some(\n (l) => l !== semantic && l.unique && (l.strategy === "stable_attribute" || l.strategy === "relational" && !l.expression.includes(name))\n );\n }\n function compareLocators(a, b) {\n if (a.unique !== b.unique) return a.unique ? -1 : 1;\n const idA = isExplicitIdentifier(a);\n const idB = isExplicitIdentifier(b);\n if (idA !== idB) return idA ? -1 : 1;\n return STRATEGY_ORDER.indexOf(a.strategy) - STRATEGY_ORDER.indexOf(b.strategy);\n }\n function buildLocatorSet(el) {\n const base = { sibling_index: nthOfType(el), ancestors: ancestorContext(el) };\n const locators = [];\n const semantic = semanticCandidate(el);\n if (semantic) locators.push(build("semantic", el, semantic, { ...base, anchor: null }));\n const attribute = pickBest(el, attributeCandidates(el, true));\n if (attribute) locators.push(build("stable_attribute", el, attribute, { ...base, anchor: null }));\n const relational = relationalCandidate(el);\n if (relational)\n locators.push(\n build("relational", el, relational.candidate, { ...base, anchor: relational.anchor })\n );\n locators.push(build("css", el, structuralCss(el), { ...base, anchor: null }));\n locators.push(build("xpath", el, structuralXPath(el), { ...base, anchor: null }));\n locators.sort(compareLocators);\n const families = new Set(\n locators.map((l) => l.strategy).filter((s) => INDEPENDENT_FAMILIES.has(s))\n );\n const independent = Math.max(1, Math.min(3, families.size));\n const hasUnique = locators.some((l) => l.unique);\n const reasons = [];\n const required = hasUniqueExplicitIdentifier(locators) || hasUniqueNamedSemanticWithBackup(locators) ? REQUIRED_STRATEGIES_WITH_ID : REQUIRED_STRATEGIES;\n if (independent < required) {\n const missing = Array.from(INDEPENDENT_FAMILIES).filter((s) => !families.has(s));\n reasons.push(\n `only ${independent} independent strateg${independent === 1 ? "y" : "ies"} (no ${missing.join(" or ")} locator could be built)`\n );\n }\n if (!hasUnique) {\n reasons.push("no locator matches exactly one element");\n } else if (!locators.some((l) => l.unique && l.stability !== "volatile")) {\n reasons.push("only position-based locators are unique");\n }\n const needsReview = reasons.length > 0;\n return {\n locators,\n independent_strategy_count: independent,\n has_unique: hasUnique,\n needs_review: needsReview,\n review_reason: needsReview ? reasons.join("; ") : null\n };\n }\n\n // src/sha256.ts\n var K = new Uint32Array([\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n ]);\n var rotr = (x, n) => x >>> n | x << 32 - n;\n function sha256Hex(data) {\n const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);\n padded.set(data);\n padded[data.length] = 128;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor(data.length / 536870912));\n view.setUint32(padded.length - 4, data.length << 3 >>> 0);\n const h = new Uint32Array([\n 1779033703,\n 3144134277,\n 1013904242,\n 2773480762,\n 1359893119,\n 2600822924,\n 528734635,\n 1541459225\n ]);\n const w = new Uint32Array(64);\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\n for (let i = 16; i < 64; i++) {\n const a2 = w[i - 15];\n const b2 = w[i - 2];\n const s0 = rotr(a2, 7) ^ rotr(a2, 18) ^ a2 >>> 3;\n const s1 = rotr(b2, 17) ^ rotr(b2, 19) ^ b2 >>> 10;\n w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;\n }\n let [a, b, c, d, e, f, g, hh] = h;\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const ch = e & f ^ ~e & g;\n const t1 = hh + s1 + ch + K[i] + w[i] | 0;\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const maj = a & b ^ a & c ^ b & c;\n const t2 = s0 + maj | 0;\n hh = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b;\n b = a;\n a = t1 + t2 | 0;\n }\n const next = [a, b, c, d, e, f, g, hh];\n for (let i = 0; i < 8; i++) h[i] = h[i] + next[i] | 0;\n }\n return Array.from(h, (x) => x.toString(16).padStart(8, "0")).join("");\n }\n\n // src/family.ts\n var NTH_PICK = /\\s>>\\snth=-?\\d+\\s*$/;\n var XPATH_INDEX = /\\[\\d+\\]/;\n var CSS_NTH = /:nth-(of-type|child)\\(/;\n function withoutQuotedText(expression) {\n return expression.replace(/\'[^\']*\'|"[^"]*"/g, "\'\'");\n }\n function strategyFamily(locator) {\n const expression = locator.expression;\n if (NTH_PICK.test(expression)) return "position";\n const unquoted = withoutQuotedText(expression);\n if (locator.strategy !== "xpath" && CSS_NTH.test(unquoted)) return "position";\n if (locator.strategy === "xpath" && XPATH_INDEX.test(unquoted)) return "position";\n if (locator.strategy === "semantic") return "semantic";\n if (locator.strategy === "relational") return "relational";\n return "attribute";\n }\n\n // src/verification.ts\n var LONG_TEXT = 80;\n var MAX_WORDS = 40;\n var MAX_WORD_LENGTH = 80;\n var MAX_VALUE_LENGTH = 200;\n var IDENTIFIER_KINDS = [\n "name",\n "id",\n "type",\n "autocomplete",\n "test_id",\n "role",\n "accessible_name",\n "label_text"\n ];\n var TEST_ID_ATTRS = ["data-testid", "data-test-id", "data-test", "data-cy", "data-qa"];\n function isSecretField(el, tools) {\n if (el.tagName === "INPUT") {\n const type = (el.getAttribute("type") ?? "").toLowerCase();\n if (type === "password" || type === "hidden") return true;\n }\n return tools.isSecret(el);\n }\n function readIdentifier(el, kind) {\n let raw = null;\n if (kind === "name" || kind === "id" || kind === "type" || kind === "autocomplete") {\n raw = el.getAttribute(kind);\n } else if (kind === "test_id") {\n for (const attr of TEST_ID_ATTRS) {\n const found = el.getAttribute(attr);\n if (found !== null && found.trim() !== "") {\n raw = found;\n break;\n }\n }\n } else if (kind === "role") {\n raw = el.getAttribute("role") ?? implicitRole(el);\n } else {\n const named = accessibleName(el);\n if (named !== null) {\n const fromLabel = named.source === "label";\n if (kind === "label_text" === fromLabel) raw = named.name;\n }\n }\n if (raw === null) return null;\n const value = normalizeSpace(raw);\n return value === "" ? null : value.slice(0, MAX_VALUE_LENGTH);\n }\n function countSameValue(el, kind, value) {\n let count = 0;\n const doc = el.ownerDocument;\n for (const other of Array.from(doc.getElementsByTagName(el.tagName))) {\n if (readIdentifier(other, kind) === value) count++;\n }\n return count;\n }\n function repeatedRow(el) {\n const parent = el.parentElement;\n if (parent === null) return null;\n const tag = el.tagName;\n if (tag === "TD" || tag === "TH" || tag === "OPTION") return null;\n const role = el.getAttribute("role");\n const rowLike = tag === "TR" || tag === "LI" || role === "row" || role === "listitem";\n if (!rowLike && el.className.trim() === "") return null;\n const same = Array.from(parent.children).filter(\n (child) => child.tagName === tag && child.getAttribute("role") === role && (rowLike || child.className === el.className)\n );\n if (same.length < 2) return null;\n return { kind: rowLike ? "row" : "card", index: same.indexOf(el) };\n }\n var SKIPPED_TEXT_TAGS2 = /* @__PURE__ */ new Set([\n "SCRIPT",\n "STYLE",\n "NOSCRIPT",\n "TEXTAREA",\n "SELECT",\n "TEMPLATE"\n ]);\n function spacedText(el) {\n if (SKIPPED_TEXT_TAGS2.has(el.tagName)) return "";\n const parts = [];\n for (let child = el.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 3) parts.push(child.nodeValue ?? "");\n else if (child.nodeType === 1) parts.push(spacedText(child));\n }\n return parts.join(" ");\n }\n function wordsOf(text) {\n return text.toLowerCase().split(/\\s+/).map((word) => word.replace(/[^\\p{L}\\p{N}]/gu, "")).filter((word) => word !== "");\n }\n function rowTextOf(row, tools, keepWords) {\n const raw = normalizeSpace(spacedText(row)).trim();\n if (raw === "") return null;\n const text = normalizeSpace(tools.scrub(raw)).trim();\n if (text !== raw) return null;\n const digits = (text.match(/\\d/g) ?? []).length;\n const volatile = digits >= 2 || text.length > LONG_TEXT;\n const stable = volatile && !keepWords ? [] : wordsOf(text).filter((word) => !/\\d/.test(word)).slice(0, MAX_WORDS).map((word) => word.slice(0, MAX_WORD_LENGTH));\n return {\n stable_words: stable,\n volatile,\n length: text.length,\n hash: sha256Hex(new TextEncoder().encode(text.toLowerCase()))\n };\n }\n function readNeighbour(el, tools) {\n return neighbourOf(el, tools, false);\n }\n function neighbourOf(el, tools, keepWords) {\n let node = el.parentElement;\n while (node !== null && node.tagName !== "BODY" && node.tagName !== "HTML") {\n const tag = node.tagName;\n let kind = null;\n let rowIndex = null;\n if (tag === "FORM") kind = "form";\n else if (tag === "FIELDSET") kind = "fieldset";\n else {\n const row = repeatedRow(node);\n if (row !== null) {\n kind = row.kind;\n rowIndex = row.index;\n }\n }\n if (kind !== null) {\n const role = el.getAttribute("role") ?? implicitRole(el);\n const peers = Array.from(node.getElementsByTagName(el.tagName)).filter(\n (peer) => (peer.getAttribute("role") ?? implicitRole(peer)) === role\n );\n return {\n container_kind: kind,\n row_index: rowIndex,\n index_in_container: Math.max(0, peers.indexOf(el)),\n row_text: kind === "form" || kind === "fieldset" ? null : rowTextOf(node, tools, keepWords)\n };\n }\n node = node.parentElement;\n }\n return null;\n }\n function captureVerification(el, tools) {\n return captureWith(el, tools, false);\n }\n function captureVerificationForReplay(el, tools) {\n return captureWith(el, tools, true);\n }\n function captureWith(el, tools, keepWords) {\n const identifiers = [];\n if (!isSecretField(el, tools)) {\n for (const kind of IDENTIFIER_KINDS) {\n const value = readIdentifier(el, kind);\n if (value === null) continue;\n if (tools.scrub(value) !== value) continue;\n const unique = countSameValue(el, kind, value) === 1;\n const trusted = kind === "id" ? unique && !idVolatility(value).volatile : unique;\n identifiers.push({ kind, value, unique_at_record: trusted });\n }\n }\n return { captured_by: "recorder", identifiers, neighbour: neighbourOf(el, tools, keepWords) };\n }\n var SECRET_FIELD_HINT = /pass|pwd|secret|token|api.?key|auth|otp|cvv|cvc|card|ssn|\\bpin\\b/i;\n var UNSAFE_TEXT = /@|:\\/\\/|www\\.|\\d{4,}|(?=[A-Za-z0-9_+/=-]*\\d)(?=[A-Za-z0-9_+/=-]*[A-Za-z])[A-Za-z0-9_+/=-]{20,}/;\n var storageCaptureTools = {\n scrub: (text) => UNSAFE_TEXT.test(text) ? "[REDACTED]" : text,\n isSecret: (el) => {\n const type = (el.getAttribute("type") ?? "").toLowerCase();\n if (type === "password" || type === "hidden") return true;\n return ["name", "id", "autocomplete"].some(\n (attr) => SECRET_FIELD_HINT.test(el.getAttribute(attr) ?? "")\n );\n }\n };\n return __toCommonJS(src_exports);\n})();\n';
@@ -4449,7 +4467,7 @@ var RunCancelledError = class extends Error {
4449
4467
  };
4450
4468
 
4451
4469
  // src/runner-client.ts
4452
- var RUNNER_VERSION = "0.1.0";
4470
+ var RUNNER_VERSION = "0.1.1";
4453
4471
  var HEADER_RUNNER_VERSION = "X-Runner-Version";
4454
4472
  var HEADER_RUNNER_ID = "X-Runner-Id";
4455
4473
  var CODE_RUN_CANCELLED = "RUN_CANCELLED";
@@ -5124,7 +5142,7 @@ Options for 'run':
5124
5142
  --all Run all active test cases in the site
5125
5143
  --collection-run <id> Target an existing collection run instead of creating one
5126
5144
  --browser <name> Browser to execute ('chromium' or 'firefox', default: chromium)
5127
- --concurrency <n> Concurrent execution slots (default: 1)
5145
+ --concurrency <n> Concurrent browsers (default: 1; lowered automatically to fit this machine, at most 4)
5128
5146
  --junit <path> Write standard JUnit XML report to file path upon completion
5129
5147
  --log-level <level> Log level: debug | info | warn | error (default: info)
5130
5148
  --help, -h Show this help message
@@ -5133,7 +5151,7 @@ Options for 'run':
5133
5151
  Options for 'listen':
5134
5152
  --base-url <url> Locus API Gateway URL (or LOCUS_BASE_URL, default: http://localhost:9280)
5135
5153
  --token <token> Runner API token with RoleRunner (or LOCUS_TOKEN)
5136
- --concurrency <n> Concurrent execution slots (default: 1)
5154
+ --concurrency <n> Concurrent browsers (default: 1; lowered automatically to fit this machine, at most 4)
5137
5155
  --log-level <level> Log level: debug | info | warn | error (default: info)
5138
5156
  --help, -h Show this help message
5139
5157
 
@@ -5394,7 +5412,16 @@ async function main(args = process.argv.slice(2)) {
5394
5412
  );
5395
5413
  return 1;
5396
5414
  }
5397
- const concurrency = parseInt(values["concurrency"] || "1", 10);
5415
+ const resolved = resolveConcurrency(
5416
+ parseInt(values["concurrency"] || "1", 10),
5417
+ cpus().length,
5418
+ freemem()
5419
+ );
5420
+ if (resolved.warning !== void 0) {
5421
+ process.stderr.write(`Warning: ${resolved.warning}
5422
+ `);
5423
+ }
5424
+ const concurrency = resolved.value;
5398
5425
  const rawLogLevel = values["log-level"] ?? "info";
5399
5426
  const logLevel = rawLogLevel === "debug" || rawLogLevel === "warn" || rawLogLevel === "error" ? rawLogLevel : "info";
5400
5427
  const rawBrowser = values["browser"] ?? "chromium";
@@ -5418,7 +5445,7 @@ async function main(args = process.argv.slice(2)) {
5418
5445
  all: Boolean(values["all"]),
5419
5446
  collectionRunId: values["collection-run"],
5420
5447
  browser,
5421
- concurrency: Number.isNaN(concurrency) ? 1 : concurrency,
5448
+ concurrency,
5422
5449
  junitPath: values["junit"],
5423
5450
  logLevel
5424
5451
  });
@@ -5427,7 +5454,7 @@ async function main(args = process.argv.slice(2)) {
5427
5454
  return executeListenCommand({
5428
5455
  baseUrl,
5429
5456
  token,
5430
- concurrency: Number.isNaN(concurrency) ? 1 : concurrency,
5457
+ concurrency,
5431
5458
  logLevel
5432
5459
  });
5433
5460
  }