{"domain":{"public_id":"dom-nrmu7952t16s","revision":12},"bundle":{"url":"https://cdn.nekuda.ai/v1/bundles/17cef0bf6eb3434d422429fae763151e384ada44328faa45d36f78dae4935044.js","sha256":"17cef0bf6eb3434d422429fae763151e384ada44328faa45d36f78dae4935044"},"capabilities":[{"id":"66b6ec44-6866-4d96-a00f-f7cdd255e565","name":"ask_site","description":"Answer a visitor's question from this site's own pages (information pages, posts, listings), read when asked. Returns the best-matching sections, each with its heading, an excerpt in the site's own words and its page; nothing when the site does not say. The visitor's page stays where it is.","input_schema":{"type":"object","required":["query"],"properties":{"query":{"type":"string","minLength":1,"description":"The visitor's question, in their own words."}},"additionalProperties":false},"dependencies":[],"kind":"action","impl":{"code":"// ask_site@7 (runtime 2) — compiled from scanner-v2/harness/templates; edit the template, not this.\nconst template = {\"id\":\"ask_site\",\"version\":\"7\"};\nconst slots = {\"home\":\"/\",\"named\":\"/blog /altin-fiyatlari /samsun-kuyumcu /kampanya/indirim-vitrini /urunler\",\"pages\":{\"/altin-fiyatlari\":\"fetch\",\"/blog\":\"fetch\",\"/cerez-politikasi\":\"fetch\",\"/gizlilik-politikasi\":\"fetch\",\"/hakkimizda\":\"fetch\",\"/iletisim\":\"fetch\",\"/kampanya/indirim-vitrini\":\"fetch\",\"/kvkk\":\"fetch\",\"/mesafeli-satis-sozlesmesi\":\"fetch\",\"/samsun-kuyumcu\":\"fetch\",\"/urunler\":\"fetch\"}};\n// Runtime 2: the helpers every template stands on (scanner principle 4 — the model fills\n// slots; this tested runtime does the clicking, typing, waiting and reading). Plain browser\n// JavaScript with no imports. It is prepended to each template's tool (run by the Snippet\n// in the shopper's tab, where `document` and `location` may be the Snippet's shadows) and\n// to its check (run by the prover). Free variables: `template`, `slots`.\n// Never pass `document` or `window` themselves to a native API (they may be proxies):\n// use `document.documentElement`, and create events without a `view`.\n// Beside runtime 1 (NEK-1078): a URL's path placeholder also takes the item's own URL or\n// path (`resolveUrl`); a field spec may end `|slug` (an href's last path segment, the id\n// the item's page URL carries); `labelOf` reads the text just before an unlabelled group;\n// `ready`/`qReady` wait until a control is there and enabled (a framework re-renders it\n// after this script's turn); `pressEach` presses every match of a selector in turn.\nconst rt = (() => {\n  const PLACEHOLDER = /\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g;\n  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n  const isSet = (v) => v !== undefined && v !== null && v !== \"\";\n\n  /** Lowercased, whitespace-collapsed text, for \"does the page show X\" comparisons. */\n  function norm(value) {\n    return String(value == null ? \"\" : value)\n      .replace(/\\s+/g, \" \")\n      .trim()\n      .toLowerCase();\n  }\n\n  /** Where a query ran, for error messages: a fetched page's path, else this page's. */\n  function where(root) {\n    const doc = root && (root.__rtUrl ? root : root.ownerDocument);\n    const url = doc && doc.__rtUrl ? doc.__rtUrl : location.href;\n    try {\n      const u = new URL(url);\n      return u.pathname + u.search;\n    } catch {\n      return String(url);\n    }\n  }\n\n  function slot(name) {\n    const value = slots[name];\n    if (!isSet(value)) throw new Error(`${template.id}: slot \"${name}\" is not set`);\n    return value;\n  }\n\n  function cssString(value) {\n    return String(value).replace(/[\"\\\\]/g, \"\\\\$&\").replace(/\\n/g, \"\\\\a \");\n  }\n\n  /** A selector with its {param} placeholders filled from `input` (CSS-string-escaped). */\n  function fill(selector, input) {\n    return String(selector).replace(PLACEHOLDER, (_, key) => {\n      const value = input ? input[key] : undefined;\n      if (!isSet(value)) throw new Error(`the selector ${selector} needs \"${key}\", which the call did not give`);\n      return cssString(value);\n    });\n  }\n\n  /** A selector slot, filled. */\n  function sel(name, input) {\n    return fill(slot(name), input);\n  }\n\n  /** The element a selector slot names; throws naming the slot when nothing matches. */\n  function q(name, input, root) {\n    const selector = sel(name, input);\n    const el = (root || document).querySelector(selector);\n    if (!el) throw new Error(`slot \"${name}\" (${selector}) matched nothing on ${where(root)}`);\n    return el;\n  }\n\n  /** The element a selector slot names, or null (also when the slot is not set). */\n  function qMaybe(name, input, root) {\n    return isSet(slots[name]) ? (root || document).querySelector(sel(name, input)) : null;\n  }\n\n  function qa(name, input, root) {\n    return [...(root || document).querySelectorAll(sel(name, input))];\n  }\n\n  /** Visible text of an element (rendered text on the live page, raw text elsewhere). */\n  function text(el) {\n    if (!el) return \"\";\n    const live = el.ownerDocument && el.ownerDocument.defaultView && el.isConnected;\n    const raw = live && typeof el.innerText === \"string\" ? el.innerText : el.textContent;\n    return String(raw || \"\").replace(/\\s+/g, \" \").trim();\n  }\n\n  /** What a control holds (a select's chosen option, an input's value), else its text. */\n  function valueOf(el) {\n    if (!el) return null;\n    if (el.tagName === \"SELECT\") {\n      const option = el.selectedOptions && el.selectedOptions[0];\n      return option ? option.value || text(option) : el.value;\n    }\n    if (el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\") return el.value;\n    return text(el);\n  }\n\n  function absolute(href, base) {\n    try {\n      return new URL(href, base || location.href).href;\n    } catch {\n      return href;\n    }\n  }\n\n  /** The last non-empty path segment of a URL or path (`/gb/products/t-shirt/` → `t-shirt`). */\n  function slug(value, base) {\n    if (!isSet(value)) return value;\n    let path = String(value).trim();\n    try {\n      path = new URL(path, base || location.href).pathname;\n    } catch {}\n    const parts = path.split(\"/\").filter(Boolean);\n    if (!parts.length) return String(value).trim();\n    try {\n      return decodeURIComponent(parts[parts.length - 1]);\n    } catch {\n      return parts[parts.length - 1];\n    }\n  }\n\n  /**\n   * One field of an item: `selector`, `selector@attr`, `@attr` or `.` (see the fields slot),\n   * each optionally ending `|slug`: the value's last path segment (an item's id from the\n   * link to its own page, `a@href|slug`).\n   */\n  function field(item, rawSpec, base) {\n    const piped = /\\|\\s*slug\\s*$/.exec(rawSpec);\n    if (piped) return slug(field(item, rawSpec.slice(0, piped.index).trim(), base), base);\n    const spec = rawSpec;\n    if (spec === \".\") return valueOf(item);\n    let selector = spec;\n    let attr = null;\n    const at = spec.lastIndexOf(\"@\");\n    if (at >= 0 && /^[A-Za-z_:][-A-Za-z0-9_:.]*$/.test(spec.slice(at + 1))) {\n      selector = spec.slice(0, at).trim();\n      attr = spec.slice(at + 1);\n    }\n    const el = selector ? item.querySelector(selector) : item;\n    if (!el) return null;\n    if (!attr) return valueOf(el);\n    const raw = el.getAttribute(attr);\n    if (raw === null) return null;\n    return attr === \"href\" || attr === \"src\" || attr === \"action\" ? absolute(raw, base) : raw.trim();\n  }\n\n  /** A number from text: \"$1,234.50\", \"£9.50\", \"1.234,50 €\", \"Qty 2\". Null when none. */\n  function number(value) {\n    if (value === null || value === undefined) return null;\n    if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n    const match = String(value).replace(/\\s/g, \"\").match(/-?\\d[\\d.,']*/);\n    if (!match) return null;\n    let s = match[0].replace(/'/g, \"\").replace(/[.,]$/, \"\");\n    const comma = s.lastIndexOf(\",\");\n    const dot = s.lastIndexOf(\".\");\n    if (comma > dot) {\n      const decimals = s.length - comma - 1;\n      s = dot === -1 && decimals === 3 ? s.replace(/,/g, \"\") : s.replace(/\\./g, \"\").replace(\",\", \".\");\n    } else {\n      s = s.replace(/,/g, \"\");\n    }\n    const n = Number(s);\n    return Number.isFinite(n) ? n : null;\n  }\n\n  /** Every number in a text (for \"the page shows this price\"). */\n  function numbers(value) {\n    return (String(value || \"\").match(/-?\\d[\\d.,']*\\d|\\d/g) || []).map(number).filter((n) => n !== null);\n  }\n\n  /** A time of day as HH:MM from \"9:00 AM\", \"2:30 pm\", \"14:30\". Null when it is not one. */\n  function clock(value) {\n    const m = /(\\d{1,2})[:.h](\\d{2})\\s*([ap])?\\.?\\s*m?\\.?/i.exec(String(value || \"\"));\n    if (!m) return null;\n    let hour = Number(m[1]);\n    const minute = Number(m[2]);\n    const half = m[3] ? m[3].toLowerCase() : \"\";\n    if (half === \"p\" && hour < 12) hour += 12;\n    if (half === \"a\" && hour === 12) hour = 0;\n    if (hour > 23 || minute > 59) return null;\n    return `${String(hour).padStart(2, \"0\")}:${String(minute).padStart(2, \"0\")}`;\n  }\n\n  function coerce(name, raw) {\n    if (name === \"price\" || name === \"subtotal\" || name === \"total\") return number(raw);\n    if (name === \"quantity\") {\n      const n = number(raw);\n      return n === null ? null : Math.round(n);\n    }\n    return raw;\n  }\n\n  /** Read the fields slot `fieldsSlot` from one element. Required fields that read nothing throw. */\n  function readFields(root, fieldsSlot, base, required) {\n    const specs = slot(fieldsSlot);\n    const out = {};\n    for (const [name, spec] of Object.entries(specs)) {\n      const raw = field(root, spec, base);\n      if ((raw === null || raw === \"\") && required && required.includes(name)) {\n        throw new Error(`slot \"${fieldsSlot}\" field \"${name}\" (${spec}) read nothing on ${where(root)}`);\n      }\n      out[name] = coerce(name, raw);\n      if ((name === \"price\" || name === \"subtotal\" || name === \"total\") && isSet(raw)) {\n        out[`${name}_text`] = String(raw).trim();\n      }\n    }\n    return out;\n  }\n\n  /** Read every item a selector slot matches, each through the fields slot. */\n  function readItems(root, itemSlot, fieldsSlot, input, base) {\n    return qa(itemSlot, input, root).map((item) => readFields(item, fieldsSlot, base));\n  }\n\n  /** Is this value an item's URL or site path rather than a bare id? */\n  function urlLike(value) {\n    return typeof value === \"string\" && /^(https?:\\/\\/|\\/)/i.test(value.trim());\n  }\n\n  /**\n   * The path placeholders' values a URL or path carries for this URL slot's path, or null\n   * when its path is not one the slot makes. Matched at the end of the path, so\n   * `/collections/all/products/mug` gives `{ id: \"mug\" }` for `/products/{id}`.\n   */\n  function pathValues(pathPart, value) {\n    let path;\n    try {\n      path = new URL(String(value).trim(), location.href).pathname;\n    } catch {\n      return null;\n    }\n    const keys = [];\n    const source = pathPart\n      .replace(/\\/+$/, \"\")\n      .split(PLACEHOLDER)\n      .map((part, i) => {\n        if (i % 2) {\n          keys.push(part);\n          return \"([^/]+)\";\n        }\n        return part.replace(/[.*+?^$()|[\\]{}\\\\]/g, \"\\\\$&\");\n      })\n      .join(\"\");\n    if (!keys.length) return null;\n    const m = new RegExp(`${source}/?$`).exec(path);\n    if (!m) return null;\n    const out = {};\n    keys.forEach((key, i) => {\n      try {\n        out[key] = decodeURIComponent(m[i + 1]);\n      } catch {\n        out[key] = m[i + 1];\n      }\n    });\n    return out;\n  }\n\n  /**\n   * A URL slot filled from `values` (then `defaults`), with the values it used: path\n   * placeholders must be given, as a bare value or as the item's own URL or path (whose\n   * path the slot's path matches); a query pair whose placeholder has no value is left out.\n   */\n  function resolveUrl(template, values, defaults) {\n    const raw = String(template);\n    const cut = raw.indexOf(\"?\");\n    const pathPart = cut < 0 ? raw : raw.slice(0, cut);\n    const queryPart = cut < 0 ? \"\" : raw.slice(cut + 1);\n    const given = { ...(values || {}) };\n    for (const [key, v] of Object.entries(given)) {\n      if (!urlLike(v) || !pathPart.includes(`{${key}}`)) continue;\n      const found = pathValues(pathPart, v);\n      if (!found) {\n        throw new Error(`\"${key}\" is ${v}, which is not a page ${pathPart} names: pass its id, or the URL of its own page`);\n      }\n      Object.assign(given, found);\n    }\n    const used = {};\n    const pick = (key) => {\n      const v = isSet(given[key]) ? given[key] : isSet(defaults && defaults[key]) ? defaults[key] : null;\n      if (v !== null) used[key] = String(v);\n      return v;\n    };\n    const path = pathPart.replace(PLACEHOLDER, (_, key) => {\n      const v = pick(key);\n      if (v === null) throw new Error(`the URL ${template} needs \"${key}\", which the call did not give`);\n      return encodeURIComponent(String(v));\n    });\n    const url = new URL(path, location.href);\n    for (const pair of queryPart.split(\"&\").filter(Boolean)) {\n      const eq = pair.indexOf(\"=\");\n      const key = decodeURIComponent(eq < 0 ? pair : pair.slice(0, eq));\n      let missing = false;\n      const value = (eq < 0 ? \"\" : pair.slice(eq + 1)).replace(PLACEHOLDER, (_, k) => {\n        const v = pick(k);\n        if (v === null) missing = true;\n        return v === null ? \"\" : String(v);\n      });\n      if (!missing) url.searchParams.append(key, value);\n    }\n    return { url: url.href, values: used };\n  }\n\n  /** A URL slot filled (see {@link resolveUrl}): the URL alone. */\n  function fillUrl(template, values, defaults) {\n    return resolveUrl(template, values, defaults).url;\n  }\n\n  /** Fetch a same-origin page as a document (the shopper's cookies go with it). */\n  async function fetchDoc(url) {\n    const res = await fetch(url, { credentials: \"same-origin\", headers: { accept: \"text/html\" } });\n    if (!res.ok) throw new Error(`${where({ __rtUrl: url })} answered HTTP ${res.status}`);\n    const doc = new DOMParser().parseFromString(await res.text(), \"text/html\");\n    doc.__rtUrl = res.url || url;\n    return doc;\n  }\n\n  /** Poll `check` until it answers truthy; throws `what` after `timeoutMs`. */\n  async function waitFor(check, what, timeoutMs) {\n    const limit = timeoutMs || 10000;\n    const started = Date.now();\n    for (;;) {\n      let value;\n      try {\n        value = await check();\n      } catch {\n        value = undefined;\n      }\n      if (value) return value;\n      if (Date.now() - started > limit) throw new Error(`${what} (waited ${Math.round(limit / 1000)} s on ${where()})`);\n      await sleep(50);\n    }\n  }\n\n  /** Resolve once the page has had no DOM change for `ms` (at most `maxMs`). */\n  function quiet(ms, maxMs) {\n    const calm = ms || 250;\n    return new Promise((resolve) => {\n      let timer;\n      let cap;\n      const observer = new MutationObserver(() => {\n        clearTimeout(timer);\n        timer = setTimeout(done, calm);\n      });\n      function done() {\n        observer.disconnect();\n        clearTimeout(timer);\n        clearTimeout(cap);\n        resolve();\n      }\n      observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });\n      timer = setTimeout(done, calm);\n      cap = setTimeout(done, maxMs || 5000);\n    });\n  }\n\n  /** The real click sequence a person's mouse makes: over, down, focus, up, click. */\n  function click(el) {\n    try {\n      el.scrollIntoView({ block: \"center\", inline: \"center\" });\n    } catch {}\n    const rect = el.getBoundingClientRect();\n    const at = { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 };\n    const base = { bubbles: true, cancelable: true, composed: true, button: 0, ...at };\n    const Pointer = typeof PointerEvent === \"function\" ? PointerEvent : MouseEvent;\n    const pointer = { ...base, pointerType: \"mouse\", isPrimary: true };\n    el.dispatchEvent(new Pointer(\"pointerover\", pointer));\n    el.dispatchEvent(new MouseEvent(\"mouseover\", base));\n    el.dispatchEvent(new Pointer(\"pointerdown\", { ...pointer, buttons: 1 }));\n    el.dispatchEvent(new MouseEvent(\"mousedown\", { ...base, buttons: 1 }));\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    el.dispatchEvent(new Pointer(\"pointerup\", pointer));\n    el.dispatchEvent(new MouseEvent(\"mouseup\", base));\n    el.click();\n  }\n\n  /** Is a control switched off (disabled, or aria-disabled)? */\n  function isDisabled(el) {\n    return Boolean(el.disabled) || el.getAttribute(\"aria-disabled\") === \"true\";\n  }\n\n  /**\n   * The control `find` returns (a function, or a selector on this page), once it is there\n   * and enabled: a framework draws a pick's effect after the script's turn (Add stays\n   * disabled until the size just chosen renders). After `timeoutMs` (5 s) it throws that\n   * `subject` matched nothing, or stays disabled, on `root`'s page (else this one).\n   */\n  async function ready(find, subject, timeoutMs, root) {\n    const get = typeof find === \"function\" ? find : () => document.querySelector(find);\n    const limit = timeoutMs || 5000;\n    const started = Date.now();\n    for (;;) {\n      let el = null;\n      try {\n        el = get();\n      } catch {}\n      if (el && el.isConnected && !isDisabled(el)) return el;\n      if (Date.now() - started > limit) {\n        const state = el && el.isConnected ? \"stays disabled\" : \"matched nothing\";\n        throw new Error(`${subject} ${state} on ${where(root)} (waited ${Math.round(limit / 1000)} s)`);\n      }\n      await sleep(50);\n    }\n  }\n\n  /** The element a selector slot names, once it is there and enabled. */\n  function qReady(name, input, root, timeoutMs) {\n    const selector = sel(name, input);\n    return ready(() => (root || document).querySelector(selector), `slot \"${name}\" (${selector})`, timeoutMs, root);\n  }\n\n  /**\n   * Press every element `selector` matches (on `root`, else this page), in page order, each\n   * once it is there and enabled, the page given a moment between presses — e.g. the first\n   * choice of each option group, before an Add button that needs them.\n   */\n  async function pressEach(selector, root, what) {\n    const scope = root || document;\n    const count = scope.querySelectorAll(selector).length;\n    if (!count) throw new Error(`${what}: ${selector} matched nothing on ${where(scope.documentElement || scope)}`);\n    for (let i = 0; i < count; i++) {\n      const el = await ready(() => scope.querySelectorAll(selector)[i], `${what}: match ${i + 1} of ${selector}`, 0, root);\n      click(el);\n      await sleep(150);\n    }\n    return count;\n  }\n\n  /**\n   * A check's seed: press `picks` (every match, see {@link pressEach}; none when null), then\n   * the add control `button` once it is enabled (both selectors, on `root`, else this page).\n   * A page still hydrating ignores the first presses, so picks that leave the button\n   * disabled are pressed again, twice at most. Throws a sentence naming the slots.\n   */\n  async function seed(picks, button, root, what) {\n    const scope = root || document;\n    const label = what || \"the seed\";\n    for (let round = 1; ; round++) {\n      if (picks) await pressEach(picks, scope, `${label}'s picks`);\n      try {\n        const el = await ready(() => scope.querySelector(button), \"\", 4000, root);\n        click(el);\n        return;\n      } catch {}\n      if (round >= 3) {\n        const there = scope.querySelector(button);\n        throw new Error(\n          !there\n            ? `${label}: its add control ${button} is not on ${where(scope.documentElement || scope)}`\n            : picks\n              ? `${label}: its add control ${button} stays disabled after pressing ${picks}`\n              : `${label}: its add control ${button} stays disabled; when adding needs a choice first (a size, a colour), name those controls in seed_picks`,\n        );\n      }\n    }\n  }\n\n  /** Set a control's value the way the page's framework sees a person do it. */\n  function setNative(el, value) {\n    const proto =\n      el.tagName === \"SELECT\"\n        ? HTMLSelectElement.prototype\n        : el.tagName === \"TEXTAREA\"\n          ? HTMLTextAreaElement.prototype\n          : HTMLInputElement.prototype;\n    const descriptor = Object.getOwnPropertyDescriptor(proto, \"value\");\n    if (descriptor && descriptor.set) descriptor.set.call(el, value);\n    else el.value = value;\n  }\n\n  function setValue(el, value) {\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    setNative(el, String(value));\n    el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"insertReplacementText\", data: String(value) }));\n    el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n  }\n\n  /** Type into a text box key by key (keydown, keypress, input, keyup), then change. */\n  async function type(el, value) {\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    setNative(el, \"\");\n    el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"deleteContentBackward\" }));\n    for (const ch of String(value)) {\n      const key = { key: ch, bubbles: true, cancelable: true };\n      el.dispatchEvent(new KeyboardEvent(\"keydown\", key));\n      el.dispatchEvent(new KeyboardEvent(\"keypress\", key));\n      setNative(el, el.value + ch);\n      el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"insertText\", data: ch }));\n      el.dispatchEvent(new KeyboardEvent(\"keyup\", key));\n      await sleep(5);\n    }\n    el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n  }\n\n  /** Press Enter in a box; like a browser, submit its form unless the page handled the key. */\n  function pressEnter(el) {\n    const init = { key: \"Enter\", code: \"Enter\", keyCode: 13, which: 13, bubbles: true, cancelable: true };\n    const unhandled = el.dispatchEvent(new KeyboardEvent(\"keydown\", init));\n    el.dispatchEvent(new KeyboardEvent(\"keypress\", init));\n    if (unhandled && el.form) {\n      if (typeof el.form.requestSubmit === \"function\") el.form.requestSubmit();\n      else el.form.submit();\n    }\n    el.dispatchEvent(new KeyboardEvent(\"keyup\", init));\n  }\n\n  /**\n   * The label a person reads for a control: its <label>, aria-label or aria-labelledby, a\n   * fieldset's legend, a wrapping label, its name — or, for a group drawn without any (a\n   * row of size buttons), the short text just before it (\"Select Size\" → \"Size\").\n   */\n  function labelOf(el) {\n    const doc = el.ownerDocument;\n    if (el.id && doc) {\n      const label = doc.querySelector(`label[for=\"${cssString(el.id)}\"]`);\n      if (label) return text(label);\n    }\n    const aria = el.getAttribute(\"aria-label\");\n    if (aria) return aria.trim();\n    const by = el.getAttribute(\"aria-labelledby\");\n    if (by && doc) {\n      const named = by\n        .split(/\\s+/)\n        .map((id) => text(doc.getElementById(id)))\n        .filter(Boolean)\n        .join(\" \");\n      if (named) return named;\n    }\n    const legend = el.tagName === \"FIELDSET\" ? el.querySelector(\"legend\") : null;\n    if (legend) return text(legend);\n    const wrap = el.closest(\"label\");\n    if (wrap && wrap !== el) return text(wrap);\n    if (el.getAttribute(\"name\")) return el.getAttribute(\"name\");\n    const before = el.previousElementSibling;\n    if (before && !before.querySelector(\"button, input, select, textarea, a\")) {\n      const said = text(before)\n        .replace(/^(select|choose|pick)\\s+(a\\s+|an\\s+|your\\s+)?/i, \"\")\n        .replace(/\\s*[:*]\\s*$/, \"\");\n      // A label is a few words (\"Size\"), not a price or a count beside the group.\n      if (said && said.length <= 40 && /[a-z]/i.test(said) && !/\\d/.test(said)) return said;\n    }\n    return \"\";\n  }\n\n  /** The choices of an option control: a select, a radio group, or a group of buttons. */\n  function choices(control) {\n    if (control.tagName === \"SELECT\") {\n      return [...control.options].map((o) => ({ label: text(o), value: o.value }));\n    }\n    const radios = [...control.querySelectorAll(\"input[type=radio], input[type=checkbox]\")];\n    if (radios.length) return radios.map((r) => ({ label: labelOf(r) || r.value, value: r.value, el: r }));\n    return [...control.querySelectorAll(\"button, [role=radio], [role=option]\")].map((b) => ({\n      label: text(b),\n      value: b.getAttribute(\"data-value\") || b.value || text(b),\n      el: b,\n    }));\n  }\n\n  /** An option control read as { name, values: [{ label, value }] }. */\n  function readOption(control) {\n    return { name: labelOf(control), values: choices(control).map(({ label, value }) => ({ label, value })) };\n  }\n\n  /** Pick `wanted` (a label or a value, any case) on an option control, as a person would. */\n  function choose(control, wanted, what) {\n    const want = norm(wanted);\n    const options = choices(control);\n    const hit = options.find((o) => norm(o.value) === want || norm(o.label) === want);\n    if (!hit) {\n      throw new Error(`${what}: no choice \"${wanted}\" (choices: ${options.map((o) => o.label).join(\", \")})`);\n    }\n    if (control.tagName === \"SELECT\") setValue(control, hit.value);\n    else click(hit.el);\n    return hit.label;\n  }\n\n  /** Where a link or a GET form's submit control goes; null for a POST form or no target. */\n  function controlTarget(el, base) {\n    const link = el.closest(\"a[href]\");\n    if (link) return absolute(link.getAttribute(\"href\"), base);\n    const form = el.form || el.closest(\"form\");\n    if (!form) return null;\n    const method = (el.getAttribute(\"formmethod\") || form.getAttribute(\"method\") || \"get\").toLowerCase();\n    if (method !== \"get\") return null;\n    const url = new URL(el.getAttribute(\"formaction\") || form.getAttribute(\"action\") || base, base);\n    url.search = \"\";\n    for (const control of form.elements) {\n      if (!control.name || control.disabled) continue;\n      const type = (control.type || \"\").toLowerCase();\n      if ([\"submit\", \"button\", \"image\", \"reset\", \"file\"].includes(type) && control !== el) continue;\n      if ((type === \"checkbox\" || type === \"radio\") && !control.checked) continue;\n      url.searchParams.append(control.name, control.value || \"\");\n    }\n    return url.href;\n  }\n\n  /** Go to `url` once the tool has returned (the Snippet defers a location change). */\n  function navigate(url) {\n    location.assign(url);\n  }\n\n  /** The live page's visible text, normalized. */\n  function pageText() {\n    return norm(document.body ? document.body.innerText : \"\");\n  }\n\n  /**\n   * A same-origin page's text as the site serves it now, normalized (fetched fresh; its\n   * scripts, styles and templates left out, so only what a person could read counts).\n   */\n  async function servedText(url) {\n    const doc = await fetchDoc(url);\n    if (!doc.body) return \"\";\n    doc.body.querySelectorAll(\"script, style, noscript, template\").forEach((el) => el.remove());\n    return norm(doc.body.textContent);\n  }\n\n  /** Does `path` match an SDK page pattern (`*` = any run of characters)? */\n  function matchPath(pattern, path) {\n    const escape = (part) => part.replace(/[.+?^$()|[\\]{}\\\\]/g, \"\\\\$&\");\n    const source = String(pattern).split(\"*\").map(escape).join(\".*\");\n    return new RegExp(\"^\" + source + \"$\").test(path);\n  }\n\n  /** A form field a person has typed into (hidden fields and buttons don't count). */\n  function isTyped(field) {\n    const type = (field.type || \"text\").toLowerCase();\n    if ([\"hidden\", \"submit\", \"button\", \"image\", \"reset\", \"checkbox\", \"radio\"].includes(type)) return false;\n    if (field.tagName === \"SELECT\") return false;\n    return isSet(field.value);\n  }\n\n  return {\n    sleep, norm, where, slot, fill, sel, q, qMaybe, qa, text, valueOf, field, slug, number,\n    numbers, clock, readFields, readItems, urlLike, resolveUrl, fillUrl, fetchDoc, waitFor,\n    quiet, click, isDisabled, ready, qReady, pressEach, seed, setValue, type, pressEnter, labelOf,\n    readOption, choose, controlTarget, navigate, pageText, servedText, matchPath, isTyped,\n  };\n})();\n// ask_site@7 — answers a visitor's question from the site's own pages, read live when asked.\n// The visitor's page stays where it is: pages are fetched, or drawn in a hidden frame, and the\n// site's own data (the JSON its pages load) is read as the site sends it.\n// Slots: home (the site's entry page), pages (path → \"fetch\" | \"frame\"), data (a same-origin\n// data URL → the page that shows it and the fields a visitor sees there), named (the pages the\n// plan names, filled by the Scanner), topics (a page's phrase → a visitor's words), open (the\n// controls a page hides its text behind).\n// Every page it is given is read, several at once, within the call's time: the page in view,\n// home, the pages the plan names, then the others listed. A page it could not read in time, or\n// that held no text of its own, is said so (`unread`), never dropped without a word.\n// Beside @2 (NEK-1087: @3, then @4), for questions asked in a visitor's words, not the page's: a\n// sentence under a heading holding the words ranks above one merely mentioning them; the site's\n// own name (in nearly every page's title) need not be in the answer; words match across their\n// endings (ogród, ogrodzie) and a heading set on two lines keeps its words apart; the question\n// words of other languages count for nothing, as English ones do; a question for a price, a\n// duration, opening hours, a phone number, an email or an address is matched by one on the\n// page; an excerpt carries the lines around its sentence (a table's row, a label's value); a\n// page asked about by its title lists its sections; up to five entries, three a page; and\n// every call reads its pages anew (@2 kept the pages it read on the visitor's page and answered\n// later questions from that copy, not from what the site says when asked). Beside @3: a page is\n// fetched as the server sends it now, never the browser's cached copy (a question asked again\n// read the cache, so the site sent nothing while it was answered); and an answer that finds\n// nothing names the pages it could not read in its message, not in a list beside its empty\n// items (a decline lists nothing).\n// Beside @4 (NEK-1089), for facts a visitor sees that no page's HTML holds:\n// - text a visitor reveals with a click is read: in a frame, each closed disclosure of the\n//   page's own content (an accordion's header, a tab) is pressed in turn, and so is each\n//   control `open` names (a class's card that opens its details), one at a time, and what\n//   each shows is read; a fetched page holding such a control whose panel the server did not\n//   send is drawn in a frame so it can be;\n// - the site's own data (slot data): the JSON its pages load, read live, each record a\n//   section under its name, its fields' values its lines; a `{key}` in a data URL is filled\n//   with each record's `key` in the data read before it (an index's ids → each item's own\n//   data), a few rounds deep; a client-rendered site that refuses frames is read this way;\n// - a frame's page that drew its data from the browser's cache (a page read again) has that\n//   data read again from the site, so what it shows is what the site sends as it is asked;\n// - it only reads: a control it presses shows text (a disclosure, a tab, a \"more\" control, an\n//   item's card), never one inside a form, a link to another page or one named for an action\n//   (add, book, pay, delete, sign out…), and a data URL naming a change to the visitor's state\n//   (logout, delete, cancel, checkout, pay…) is never read; data is read only as JSON.\n// Beside @6 (NEK-1161): a page's own text is its one `main` landmark, or its whole body when it\n// has several — an Ant Design app draws each Layout.Content as a <main> (idurar: the side\n// panel's tagline first, the sign-in or password form in the second), and @6 read only the\n// first, so every page of the app read as the same tagline and none answered for its own.\nconst TOPICS = slots.topics || {};\nconst OPEN = slots.open || \"\";\n/** A page of this site, as its path; or why it is not one. */\nfunction siteUrl(slot, page) {\n  let url = null;\n  try {\n    url = new URL(page, location.href);\n  } catch {}\n  if (!url || url.origin !== location.origin) {\n    throw new Error(\n      `slot ${slot}: ${page} is not a page of this site (${location.origin}); a tool in the visitor's tab reads only this site's own pages, so leave another site's pages out`,\n    );\n  }\n  return url.pathname + url.search;\n}\n/** The site's front door (the page a visitor enters by): \"what is this site\" is answered there. */\nconst HOME = siteUrl(\"home\", slots.home);\n/** The pages to read, by path; a URL of this site is taken as its path. */\nconst PAGES = {};\nfor (const [page, how] of Object.entries(slots.pages || {})) {\n  if (how !== \"fetch\" && how !== \"frame\") {\n    throw new Error(`slot pages: ${page} is ${JSON.stringify(how)}; a page is read by \"fetch\" or \"frame\"`);\n  }\n  PAGES[siteUrl(\"pages\", page)] = how;\n}\nconst MAX_LISTED = 60; // pages a call is given (home, named, listed), at most\nif (Object.keys(PAGES).length > MAX_LISTED) {\n  throw new Error(\n    `slot pages: ${Object.keys(PAGES).length} pages; a call reads at most ${MAX_LISTED}, so list the information pages and the ones the plan names, and leave a catalog's items to its index`,\n  );\n}\n/** The pages the plan names, in its order (filled by the Scanner): read first after home. */\nconst NAMED = [];\nfor (const page of String(slots.named || \"\").split(/\\s+/)) {\n  if (!page) continue;\n  try {\n    const path = siteUrl(\"named\", page);\n    if (!NAMED.includes(path)) NAMED.push(path);\n  } catch {}\n}\n/**\n * The word of a URL that names a change to the visitor's state (signing out, deleting, paying),\n * if any: a data URL holding one is never read — a site may sign out on a GET.\n */\nconst CHANGES = /\\b(?:log ?out|log ?off|sign ?out|sign ?off|delete|remove|cancel|unsubscribe|check ?out|pay|destroy|revoke)\\b/;\nconst changeIn = (url) => {\n  const m = CHANGES.exec(\n    String(url)\n      .replace(/\\{[^}]*\\}/g, \" \")\n      .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n      .toLowerCase()\n      .replace(/[^a-z0-9]+/g, \" \"),\n  );\n  return m ? m[0] : null;\n};\n/** A `{key}` in a data URL (or its page): filled with a record's `key`. */\nconst PLACEHOLDER = /\\{([A-Za-z0-9_$-]+)\\}/g;\n/**\n * The site's own data: each URL (its placeholders kept), the fields a visitor sees there, and\n * the page that shows them (entries cite it as their link).\n */\nconst DATA = [];\nfor (const [url, how] of Object.entries(slots.data || {})) {\n  const bare = String(url).replace(PLACEHOLDER, \"x\");\n  siteUrl(\"data\", bare); // throws for another site's data\n  const at = new URL(bare, location.href);\n  const template = String(url).startsWith(\"/\") ? String(url) : String(url).slice(at.origin.length);\n  const words = String(how == null ? \"\" : how).trim().split(/\\s+/).filter(Boolean);\n  const page = words.find((w) => w.startsWith(\"/\")) || null;\n  if (page) siteUrl(\"data\", page.replace(PLACEHOLDER, \"x\"));\n  const change = changeIn(template);\n  if (change) {\n    throw new Error(\n      `slot data: ${url} names a change to the visitor's state (\"${change}\"); ask_site reads only the data a page shows (a GET of JSON), never a URL that signs out, deletes, removes, cancels, unsubscribes, checks out or pays`,\n    );\n  }\n  const fields = words.filter((w) => !w.startsWith(\"/\"));\n  if (!fields.length) {\n    throw new Error(\n      `slot data: ${url} names no fields; give the page that shows it and the fields a visitor sees there (\"/classes title schedule price materials\")`,\n    );\n  }\n  DATA.push({ template, keys: [...template.matchAll(PLACEHOLDER)].map((m) => m[1]), fields, page });\n}\nconst FETCHES = 6; // pages fetched at once\nconst FRAMES = 3; // pages drawn in hidden frames at once (each runs the page's own scripts)\nconst REVEALS = 16; // controls pressed on one frame's page, at most\nconst DATA_ROUNDS = 3; // rounds of data URLs filled from the data read before them\nconst DATA_MAX = 60; // data URLs read in one call, at most\nconst MORE = 3; // rounds of an index's next pages (Next, Older posts) read after it\nconst MORE_PAGES = 6; // next pages read, at most\nconst FOLLOW = 4; // pages linked from the ones read whose link text matches the question\nconst TOP = 5; // entries returned\nconst PER_PAGE = 3; // entries from one page, at most\n// A call answers in bounded time: an agent waits on it, and the prover gives a call 30 s. Pages\n// are read side by side until the budget runs out, and the answer comes from what was read by\n// then; what was not read is named in `unread`.\nconst BUDGET_MS = 20000;\nconst started = Date.now();\nconst left = () => BUDGET_MS - (Date.now() - started);\n\nconst question = String(input.query == null ? \"\" : input.query).trim();\nif (!question) throw new Error(\"query is empty: ask a question about this site\");\n\n// ── Words: a question's meaningful words, compared by stem ──\nconst STOP = new Set(\n  (\n    \"a an the and or but nor of to in on at by for from with without about into onto over under as \" +\n    \"is are was were be been being am do does did done doing have has had can could will would \" +\n    \"shall should may might must me my mine we our ours us you your yours he him his she her it its \" +\n    \"they them their this that these those there here what which who whom whose when where why how \" +\n    \"much many any some all each every more most other than then so if not no yes please tell know \" +\n    \"want need like get got give find show let make use using thing things something anything \" +\n    \"instead rather also just only really even still very too way long take takes \" +\n    \"site website web page pages app blog store shop company sell sells selling offer offers provide \" +\n    \"list lists listed available \" +\n    // A visitor asks in the site's language: the question words and commonest little words of\n    // Polish, German, French, Spanish, Italian, Portuguese and Dutch, less those that are English\n    // words as well (die, war, hat, come, dove, son, van, met, per, comment, hoe).\n    \"jaki jaka jakie jakich jakim jakiej ktory ktora ktore ktorych kiedy gdzie czy jest był była było \" +\n    \"bedzie macie mamy maja mozna moge mozecie prosze dla przez oraz jestem jestescie jestesmy sie ile \" +\n    \"czego kto kogo tego tej takze albo lub jak \" +\n    \"wer wie wann warum welche welcher welches welchen gibt ist sind habt haben kann konnen ich wir ihr \" +\n    \"sie der das dem des ein eine einen einem einer und oder fur mit von bei zum zur auf aus nach wieviel \" +\n    \"quel quelle quels quelles sont avez avons pouvez peut peux combien pourquoi quand vous nous les une \" +\n    \"pour avec dans sur que qui quoi est ces cette votre vos notre nos \" +\n    \"cual cuales como cuanto cuanta cuantos cuantas cuando donde por para con los las unos unas del \" +\n    \"tienen tiene tienes puedo pueden puede esta estan ustedes usted este esto \" +\n    \"che qual quale quali quanto quanta quanti quante quando sono avete abbiamo potete posso puo uno dei \" +\n    \"delle degli gli della dello nel nella sul sulla voi noi \" +\n    \"quais onde voces tem uma umas uns dos das pelo pela sao estao \" +\n    \"wat waar wanneer welke welk zijn heeft hebben hebt jullie een het voor bij naar kunnen ook\"\n  ).split(\" \"),\n);\nconst SUFFIXES = [\"ibility\", \"ability\", \"ations\", \"ation\", \"ities\", \"ings\", \"ible\", \"able\", \"ing\", \"ies\", \"ied\", \"ers\", \"ity\", \"ed\", \"er\", \"es\", \"ly\", \"s\"];\nconst stem = (w) => {\n  for (const s of SUFFIXES) if (w.length - s.length >= 4 && w.endsWith(s)) return w.slice(0, -s.length);\n  return w;\n};\nconst tokens = (s) =>\n  String(s == null ? \"\" : s)\n    .toLowerCase()\n    .normalize(\"NFKD\")\n    .replace(/[̀-ͯ]/g, \"\")\n    .match(/[\\p{L}\\p{N}]+/gu) || [];\nconst keyWords = (s) => [\n  ...new Set(\n    tokens(s)\n      .filter((w) => (w.length >= 3 || (w.length === 2 && /\\d/.test(w))) && !STOP.has(w))\n      .map(stem),\n  ),\n];\nconst same = (a, b) => {\n  if (a === b) return true;\n  const [s, l] = a.length <= b.length ? [a, b] : [b, a];\n  if (s.length >= 3 && l.startsWith(s) && (s.length >= 4 || l.length - s.length <= 2)) return true;\n  // One word in two forms (ogród, ogrodzie; lekcja, lekcjach; married, marriage): a shared\n  // stem of five letters or more, each ending at most four letters past it.\n  let p = 0;\n  while (p < s.length && s[p] === l[p]) p++;\n  return p >= 5 && s.length - p <= 4 && l.length - p <= 4;\n};\nconst flat = (s) => ` ${tokens(s).join(\" \")} `;\nconst clean = (s) => String(s == null ? \"\" : s).replace(/\\s+/g, \" \").trim();\nconst asked = keyWords(question);\nconst topics = Object.entries(TOPICS)\n  .map(([phrase, words]) => ({ phrase: flat(phrase), words: keyWords(words) }))\n  .filter((t) => t.phrase.trim() && t.words.length);\n/** The topic that routes word `w` to text holding its phrase, if any. */\nconst topicFor = (w, ...texts) =>\n  topics.find((t) => t.words.some((x) => same(x, w)) && texts.some((f) => f.includes(t.phrase)));\n\n// ── Pages: sections under their headings, and the links they carry ──\nconst pathOf = (href) => {\n  try {\n    const u = new URL(href, location.href);\n    return u.origin === location.origin ? u.pathname + u.search : null;\n  } catch {\n    return null;\n  }\n};\nconst SKIP = \"script, style, noscript, template, svg, canvas, iframe, nav, [role=navigation]\";\nconst HEAD = \"h1, h2, h3, h4, h5, h6, [role=heading], summary, dt, button[aria-expanded]\";\n/**\n * A term of a list of labels and values (\"Level\" / \"Beginner\", \"Email\" / an address): a line of its\n * list, read with the values around it, not a heading of its own. A term with a long description\n * (a question and its answer) stays a heading.\n */\nconst label = (n) => {\n  if (n.tagName !== \"DT\") return false;\n  const dd = n.nextElementSibling;\n  return !!dd && dd.tagName === \"DD\" && clean(dd.textContent).length <= 80 && clean(n.textContent).length <= 40;\n};\nconst BLOCK = new Set(\n  \"P LI DD DT TD TH BLOCKQUOTE PRE FIGCAPTION LABEL OPTION H1 H2 H3 H4 H5 H6 DIV SECTION ARTICLE ASIDE MAIN HEADER FOOTER FORM FIELDSET LEGEND TABLE TR UL OL DL DETAILS SUMMARY BODY BUTTON\".split(\" \"),\n);\n\n/**\n * An element's words, text node by text node, as its text is read everywhere else: a heading\n * set on two lines (`<span>Godziny</span><br><span>otwarcia</span>`) is two words, not\n * `Godzinyotwarcia` as its textContent runs them together.\n */\nfunction wordsOf(el) {\n  const out = [];\n  const walk = (n) => {\n    for (let c = n.firstChild; c; c = c.nextSibling) {\n      if (c.nodeType === 3) out.push(c.nodeValue);\n      else if (c.nodeType === 1 && !c.matches(SKIP)) walk(c);\n    }\n  };\n  if (el) walk(el);\n  return clean(out.join(\" \"));\n}\n\n/**\n * What a page shows of its own: its `main` landmark when it has one, else its body. A page with\n * several (an Ant Design app draws each Layout.Content as a <main>: a side panel's, then the\n * form's) names none of them its own, so all of it is read.\n */\nfunction rootOf(doc) {\n  const mains = [...doc.querySelectorAll(\"main, [role=main]\")].filter(\n    (m) => !m.hidden && !m.parentElement?.closest(\"main, [role=main]\"),\n  );\n  return mains.length === 1 ? mains[0] : doc.body;\n}\n\nfunction pageOf(doc, path) {\n  const root = rootOf(doc);\n  if (!root) return null;\n  const h1 = doc.querySelector(\"h1\");\n  const title = clean(doc.title);\n  const name = wordsOf(h1) || title || path;\n  const meta = doc.querySelector('meta[name=\"description\"]');\n  const sections = [];\n  let section = { name, link: null, lines: [] };\n  let line = [];\n  let block = null;\n  let heading = null;\n  const flush = () => {\n    const t = clean(line.join(\" \"));\n    if (t) section.lines.push(t);\n    line = [];\n  };\n  const close = () => {\n    flush();\n    if (section.lines.length || section.name !== name) sections.push(section);\n  };\n  // No filter function: nodes the browser hands to one of this tool's functions become this\n  // window's objects, so a frame's own scripts would no longer see them as elements of theirs\n  // (`instanceof Element` fails and a pressed accordion stays shut). Skipped parts are stepped over.\n  const walker = root.ownerDocument.createTreeWalker(root, 5);\n  const skip = (n) => n.nodeType === 1 && n.matches(SKIP);\n  const past = () => {\n    for (;;) {\n      const s = walker.nextSibling();\n      if (s) return s;\n      if (!walker.parentNode()) return null;\n    }\n  };\n  for (let n = walker.nextNode(); n; n = skip(n) ? past() : walker.nextNode()) {\n    if (skip(n)) continue;\n    if (heading && !heading.contains(n)) heading = null;\n    if (n.nodeType === 1) {\n      const head = !heading && n.matches(HEAD) && !label(n) ? wordsOf(n) : \"\";\n      if (head) {\n        close();\n        const a = n.querySelector(\"a[href]\") || n.closest(\"a[href]\");\n        const link = a ? pathOf(a.getAttribute(\"href\")) : null;\n        section = { name: head.slice(0, 160), link: link !== path ? link : null, lines: [] };\n        heading = n;\n      }\n      continue;\n    }\n    if (heading || !n.nodeValue.trim()) continue;\n    let b = n.parentElement;\n    while (b && !BLOCK.has(b.tagName)) b = b.parentElement;\n    if (b !== block) {\n      flush();\n      block = b;\n    }\n    line.push(n.nodeValue);\n  }\n  close();\n  const links = [];\n  for (const a of root.querySelectorAll(\"a[href]\")) {\n    if (links.length >= 400) break;\n    if (a.closest(\"nav, [role=navigation]\")) continue;\n    const to = pathOf(a.getAttribute(\"href\"));\n    const text = clean(a.textContent);\n    if (to && text && to !== path) links.push({ text: text.slice(0, 160), path: to });\n  }\n  // An index's next page: rel=next, or a link saying Next / Older (pagination sits in a nav too).\n  const nextLink = [...doc.querySelectorAll(\"a[href]\")].find(\n    (a) =>\n      (a.getAttribute(\"rel\") || \"\").split(/\\s+/).includes(\"next\") ||\n      /^(next|older)\\b|^(more posts|load more|[›»→]+)$/i.test(clean(a.textContent)),\n  );\n  const next = nextLink ? pathOf(nextLink.getAttribute(\"href\")) : null;\n  const chars = sections.reduce((n, s) => n + s.lines.join(\" \").length, 0);\n  const description = clean(meta && meta.getAttribute(\"content\"));\n  return { path, name, title, description, sections, links, next: next !== path ? next : null, chars };\n}\n\n/** Fire a pointer press on a control inside the frame (its own realm's events, no focus). */\nfunction press(el) {\n  const W = el.ownerDocument.defaultView;\n  const at = { bubbles: true, cancelable: true, composed: true, button: 0 };\n  const Pointer = typeof W.PointerEvent === \"function\" ? W.PointerEvent : W.MouseEvent;\n  el.dispatchEvent(new Pointer(\"pointerdown\", { ...at, pointerType: \"mouse\", isPrimary: true }));\n  el.dispatchEvent(new W.MouseEvent(\"mousedown\", at));\n  el.dispatchEvent(new Pointer(\"pointerup\", { ...at, pointerType: \"mouse\", isPrimary: true }));\n  el.dispatchEvent(new W.MouseEvent(\"mouseup\", at));\n  el.click();\n}\n\n/**\n * Until the frame's page has loaded and gone quiet — its text and the requests it makes both\n * still for half a second (an app loads its route's code and data after its first paint) —\n * or `until` (never past the budget).\n */\nasync function settle(doc, W, until) {\n  let last = \"\";\n  let still = 0;\n  while (Date.now() < until && left() > 250) {\n    let requests = 0;\n    try {\n      requests = W.performance.getEntriesByType(\"resource\").length;\n    } catch {}\n    const now = `${doc.readyState} ${doc.body ? doc.body.textContent.length : 0} ${requests}`;\n    if (now === last && doc.readyState === \"complete\") {\n      still += 1;\n      if (still >= 2) return;\n    } else still = 0;\n    last = now;\n    await rt.sleep(250);\n  }\n}\n\n// ── ask_site only reads: the controls it presses show text, the data it reads changes nothing ──\n/** A control's name as a visitor reads it (its label, else its text), plain: no case, no accents. */\nconst controlName = (el) =>\n  String(el.getAttribute(\"aria-label\") || el.textContent || el.getAttribute(\"value\") || el.getAttribute(\"title\") || \"\")\n    .toLowerCase()\n    .normalize(\"NFKD\")\n    .replace(/[̀-ͯ]/g, \"\")\n    .replace(/[^\\p{L}\\p{N}?]+/gu, \" \")\n    .trim();\n/**\n * Names that are an action (they add, buy, book, pay, delete, sign out, send…), in English and\n * the other languages the question words cover: a control named so is never pressed.\n */\nconst ACTS = new RegExp(\n  `^(?:${[\n    \"add\", \"buy\", \"book\", \"reserve\", \"order\", \"check ?out\", \"pay\", \"purchase\", \"place order\", \"proceed\",\n    \"delete\", \"remove\", \"cancel\", \"clear\", \"empty\", \"reset\", \"sign ?out\", \"log ?out\", \"log ?off\",\n    \"subscribe\", \"unsubscribe\", \"submit\", \"send\", \"save\", \"confirm\", \"donate\", \"register\", \"sign ?up\",\n    \"join\", \"apply\", \"claim\", \"redeem\", \"accept\", \"approve\", \"reject\", \"decline\", \"archive\", \"update\",\n    \"create\", \"upload\", \"follow\", \"unfollow\", \"like\", \"vote\", \"invite\", \"rsvp\", \"rate\",\n    \"dodaj\", \"kup\", \"kupuj\", \"zamow\", \"rezerwuj\", \"zarezerwuj\", \"zapłac\", \"zaplac\", \"usun\", \"anuluj\",\n    \"wyloguj\", \"subskrybuj\", \"zapisz\", \"wyslij\",\n    \"hinzufugen\", \"in den warenkorb\", \"kaufen\", \"jetzt kaufen\", \"buchen\", \"reservieren\", \"bestellen\",\n    \"bezahlen\", \"loschen\", \"entfernen\", \"stornieren\", \"abmelden\", \"abonnieren\", \"absenden\", \"speichern\",\n    \"ajouter\", \"acheter\", \"reserver\", \"commander\", \"payer\", \"supprimer\", \"retirer\", \"annuler\",\n    \"deconnexion\", \"se deconnecter\", \"s abonner\", \"envoyer\", \"enregistrer\", \"valider\",\n    \"anadir\", \"agregar\", \"comprar\", \"reservar\", \"pedir\", \"pagar\", \"eliminar\", \"borrar\", \"quitar\",\n    \"cancelar\", \"cerrar sesion\", \"suscribir\\\\w*\", \"enviar\", \"guardar\",\n    \"aggiungi\", \"acquista\", \"compra\", \"prenota\", \"ordina\", \"paga\", \"elimina\", \"rimuovi\", \"annulla\",\n    \"esci\", \"disconnetti\", \"iscriviti\", \"invia\", \"salva\",\n    \"adicionar\", \"encomendar\", \"excluir\", \"remover\", \"sair\", \"assinar\", \"salvar\",\n    \"toevoegen\", \"in winkelwagen\", \"kopen\", \"boeken\", \"reserveren\", \"betalen\", \"verwijderen\",\n    \"annuleren\", \"uitloggen\", \"afmelden\", \"abonneren\", \"versturen\", \"opslaan\",\n  ].join(\"|\")})\\\\b`,\n);\n/** Names that say a control shows more (\"Read more\", \"Details\"). */\nconst SHOWS =\n  /^(?:read|show|see|view|more|expand|details|continue reading|learn more|mehr|weiterlesen|plus|voir|en savoir plus|lire la suite|mas|ver|leer mas|leggi|mostra|altro|scopri|mais|saiba mais|meer|lees meer|toon|wiecej|pokaz|czytaj)\\b/;\n/**\n * Why ask_site never presses `el` (null when it may): it presses only controls that show text —\n * a disclosure or a tab by its own markup (aria-expanded, aria-haspopup, a tab, a summary), a\n * control named for showing more, or an item's card (its own text, or a heading or picture,\n * inside) — and never a form's control, a link to another page, or a control named for an action:\n * the frame shares the visitor's session, so a press there is the visitor's own.\n */\nfunction refusal(el, base) {\n  if (el.matches(\"input, select, textarea, option, [type=submit], [contenteditable]\") || el.closest(\"form\")) {\n    return \"is a form's control\";\n  }\n  const a = el.closest(\"a[href]\");\n  if (a) {\n    let to = null;\n    try {\n      to = new URL(a.getAttribute(\"href\"), base);\n    } catch {}\n    const at = new URL(base);\n    if (to && to.protocol !== \"javascript:\" && !(to.origin === at.origin && to.pathname === at.pathname && to.search === at.search)) {\n      return \"is a link to another page\";\n    }\n  }\n  const name = controlName(el);\n  if (ACTS.test(name) && !name.includes(\"?\") && name.split(\" \").length <= 6) return \"is named for an action\";\n  if (el.matches(\"[aria-expanded], [aria-haspopup], [role=tab], summary\")) return null;\n  if (SHOWS.test(name)) return null;\n  if (name.split(\" \").length >= 3 || el.querySelector(\"h1, h2, h3, h4, h5, h6, [role=heading], img, picture\")) {\n    return null;\n  }\n  return \"shows nothing by its markup or name (not a disclosure, a tab, a \\\"more\\\" control or an item's card)\";\n}\n\n/** The page a document shows, as a URL: a link on it that leads elsewhere is never pressed. */\nconst baseOf = (doc) => doc.__rtUrl || (doc.defaultView ? doc.defaultView.location.href : location.href);\n/**\n * Controls a visitor presses to show text the page holds back — a closed disclosure (an\n * accordion's header, a \"more\" toggle) or a tab — in the page's own content: not its header,\n * menus or fields, and none ask_site never presses.\n */\nconst REVEAL = '[aria-expanded=\"false\"][aria-controls], [role=\"tab\"][aria-selected=\"false\"]';\nconst CHROME =\n  \"header, nav, footer, dialog, [role=banner], [role=navigation], [role=contentinfo], [role=menu], [role=menubar], [role=dialog], [role=combobox], [role=listbox]\";\nconst revealers = (doc) =>\n  [...doc.querySelectorAll(REVEAL)].filter(\n    (el) =>\n      !el.closest(CHROME) && !el.matches(\"input, select, textarea, [role=combobox]\") && !refusal(el, baseOf(doc)),\n  );\n/**\n * A page that shows only that it is loading (an app's spinner saying \"Loading…\" while its route\n * is fetched): it has not drawn its text yet.\n */\nconst LOADING =\n  /^(?:loading|please wait|one moment|just a moment|wird geladen|laden|chargement|cargando|caricamento|carregando|ładowanie|wczytywanie)\\s*(?:\\.{1,3}|…)?$/i;\nconst loading = (p) => {\n  const lines = p ? p.sections.flatMap((s) => s.lines) : [];\n  return lines.length > 0 && lines.every((l) => LOADING.test(clean(l)));\n};\n/** No text of its own yet: none at all, or only that it is loading. */\nconst blank = (p) => !p || p.chars === 0 || loading(p);\n/**\n * Does the page hold text back that its HTML lacks: a disclosure or tab whose panel the server\n * did not send (it is drawn only when pressed)?\n */\nconst heldBack = (doc) =>\n  revealers(doc).some((el) => {\n    const id = el.getAttribute(\"aria-controls\");\n    const panel = id ? doc.getElementById(id) : null;\n    return !panel || !clean(panel.textContent);\n  });\n/** Does a response let this site draw it in a frame (X-Frame-Options, CSP frame-ancestors)? */\nfunction framable(headers) {\n  if (/deny/i.test(headers.get(\"x-frame-options\") || \"\")) return false;\n  const ancestors = /frame-ancestors([^;]*)/i.exec(headers.get(\"content-security-policy\") || \"\");\n  return !(ancestors && /'none'/i.test(ancestors[1]));\n}\n/** Until pressing changed the page's text (a panel drawn, a dialog opened), then until it settles. */\nasync function drawn(doc, before) {\n  for (let i = 0; i < 6 && left() > 250; i++) {\n    if (doc.body && doc.body.textContent.length !== before) break;\n    await rt.sleep(100);\n  }\n  let last = -1;\n  for (let i = 0; i < 10 && left() > 250; i++) {\n    const n = doc.body ? doc.body.textContent.length : 0;\n    if (n === last) return;\n    last = n;\n    await rt.sleep(150);\n  }\n}\n/** Closes a dialog pressing opened (Escape), before the next control is pressed. */\nfunction dismiss(doc) {\n  if (!doc.querySelector(\"[role=dialog], [role=alertdialog], dialog[open], [aria-modal=true]\")) return;\n  const W = doc.defaultView;\n  const at = doc.activeElement || doc.body;\n  for (const type of [\"keydown\", \"keyup\"]) {\n    at.dispatchEvent(\n      new W.KeyboardEvent(type, { key: \"Escape\", code: \"Escape\", keyCode: 27, bubbles: true, cancelable: true }),\n    );\n  }\n}\n/**\n * The page's text, with what each control shows when pressed: each closed disclosure or tab of\n * its own content, and each control `open` names, pressed one at a time (an accordion that\n * keeps one panel open, or one dialog, shows one at a time); the sections each press drew are\n * added to what the page showed.\n */\nasync function revealed(doc, path) {\n  const page = pageOf(doc, path);\n  if (!page) return null;\n  // The controls `open` names that show text: one that adds, books, pays, deletes, signs out,\n  // submits or leads away is never pressed (the check tells the builder so).\n  const own = OPEN ? [...doc.querySelectorAll(OPEN)].filter((el) => !refusal(el, baseOf(doc))) : [];\n  const controls = [...new Set([...own, ...revealers(doc)])].slice(0, REVEALS);\n  const key = (s) => `${s.name}\\n${s.lines.join(\"\\n\")}`;\n  const seen = new Set(page.sections.map(key));\n  for (const el of controls) {\n    if (left() < 1500) break;\n    if (!el.isConnected) continue;\n    const before = doc.body.textContent.length;\n    try {\n      press(el);\n    } catch {\n      continue;\n    }\n    await drawn(doc, before);\n    const now = pageOf(doc, path);\n    for (const s of now ? now.sections : []) {\n      if (!s.lines.length || seen.has(key(s))) continue;\n      seen.add(key(s));\n      page.sections.push(s);\n    }\n    try {\n      dismiss(doc);\n    } catch {}\n  }\n  page.chars = page.sections.reduce((n, s) => n + s.lines.join(\" \").length, 0);\n  return page;\n}\n\n/**\n * The site's data a frame's page drew from the browser's cache (a page read again, or one\n * whose data an earlier page loaded): read again from the site, as it is asked. Only a GET's\n * answer is ever taken from the cache, so each is a GET.\n */\nasync function reloadCached(W) {\n  let entries = [];\n  try {\n    entries = W.performance.getEntriesByType(\"resource\");\n  } catch {}\n  const urls = [\n    ...new Set(\n      entries\n        .filter(\n          (e) =>\n            (e.initiatorType === \"fetch\" || e.initiatorType === \"xmlhttprequest\") &&\n            e.encodedBodySize > 0 &&\n            e.transferSize < e.encodedBodySize,\n        )\n        .map((e) => pathOf(e.name))\n        .filter(Boolean),\n    ),\n  ].slice(0, 12);\n  await Promise.all(\n    urls.map((u) =>\n      fetch(u, { credentials: \"same-origin\", cache: \"no-store\" })\n        .then((r) => r.text())\n        .catch(() => null),\n    ),\n  );\n}\n\nlet framesOpen = 0;\n/**\n * A page as the browser draws it: loaded in a hidden same-origin frame, its held-back text\n * revealed, read, removed. At most FRAMES at once.\n */\nasync function inFrame(path) {\n  while (framesOpen >= FRAMES && left() > 0) await rt.sleep(50);\n  if (left() <= 0) return null;\n  framesOpen += 1;\n  const frame = document.createElement(\"iframe\");\n  frame.setAttribute(\"aria-hidden\", \"true\");\n  frame.tabIndex = -1;\n  frame.style.cssText =\n    \"position:fixed;left:-12000px;top:0;width:1280px;height:900px;border:0;visibility:hidden;pointer-events:none\";\n  frame.src = path;\n  document.body.append(frame);\n  const until = Date.now() + Math.max(250, Math.min(15000, left()));\n  try {\n    const doc = await rt\n      .waitFor(() => {\n        const d = frame.contentDocument;\n        return d && d.readyState !== \"loading\" && d.body && d.defaultView.location.href !== \"about:blank\" ? d : null;\n      }, `${path} to load`, Math.max(250, until - Date.now()))\n      .catch(() => null);\n    if (!doc || !doc.body) return null;\n    const W = frame.contentWindow;\n    const at = () => pathOf(W.location.href) || path;\n    // Until the page has drawn text of its own: an app shows its frame (a menu, a spinner)\n    // before its route's text, and a quiet moment can come between the two. A few seconds\n    // at most: a page with no text of its own (a gallery) is read as it is, and one that\n    // never goes quiet (it polls) as it is by then.\n    await settle(doc, W, Math.min(until, Date.now() + 5000));\n    const textBy = Math.min(until, Date.now() + 5000);\n    for (let p = pageOf(doc, at()); blank(p) && Date.now() < textBy && left() > 250; p = pageOf(doc, at())) {\n      await rt.sleep(250);\n      await settle(doc, W, textBy);\n    }\n    // A page that never drew its text in time (a \"not found\", a blank app) is not read: it is\n    // named in unread, not quoted.\n    if (doc.body.textContent.trim().length <= 50) return null;\n    const page = await revealed(doc, at());\n    // Still loading when the time for it ran out: not read, named in unread.\n    if (!page || loading(page)) return null;\n    await reloadCached(W);\n    return page;\n  } catch {\n    return null;\n  } finally {\n    frame.remove();\n    framesOpen -= 1;\n  }\n}\n\n/**\n * A page's HTML as the server sends it now: never the browser's cached copy (`no-store`), so the\n * answer is what the site says as it is asked, sent while it is asked.\n */\nasync function fetchNow(path) {\n  const res = await fetch(path, {\n    credentials: \"same-origin\",\n    cache: \"no-store\",\n    headers: { accept: \"text/html\" },\n  });\n  if (!res.ok) throw new Error(`${path} answered HTTP ${res.status}`);\n  const doc = new DOMParser().parseFromString(await res.text(), \"text/html\");\n  doc.__rtUrl = res.url || path;\n  doc.__rtFramable = framable(res.headers);\n  return doc;\n}\n\n/**\n * One page, read now: the server's HTML, never a copy kept from an earlier call (the answer is\n * what the site says as it is asked, and a call keeps nothing on the page). A page listed as\n * \"frame\" is read as the browser draws it: the frame runs the page's own scripts, so only\n * pages the builder saw send nothing but GETs on load are listed so. Any other page (home, a\n * page the plan names that is not listed, a link followed) is fetched: a GET, no scripts —\n * unless its HTML holds no text of its own (a client-rendered page, or one saying only\n * \"Loading\") or holds text back behind a control whose panel the server did not send (a\n * shop's delivery accordion): then it is drawn, as a visitor would see it, so it can be read\n * and the control pressed.\n */\nasync function read(path) {\n  if (left() <= 0) return null;\n  let page = null;\n  if (PAGES[path] === \"frame\") page = await inFrame(path);\n  else {\n    try {\n      const late = rt.sleep(Math.max(0, left())).then(() => null);\n      const doc = await Promise.race([fetchNow(path), late]);\n      if (doc) {\n        page = pageOf(doc, pathOf(doc.__rtUrl) || path);\n        if (page && doc.__rtFramable && (blank(page) || heldBack(doc))) {\n          page = (await inFrame(path)) || page;\n        }\n      }\n    } catch {}\n  }\n  // A page still saying only \"Loading\" is not read: \"Loading\" is not what the site says.\n  return page && loading(page) ? null : page;\n}\n\n// ── The site's own data: JSON its pages load, each record a section ──\n\n/** A value read as JSON when it is JSON text itself (a list an API sends inside a string). */\nfunction unwrap(v) {\n  if (typeof v === \"string\" && /^\\s*[[{]/.test(v)) {\n    try {\n      return JSON.parse(v);\n    } catch {}\n  }\n  return v;\n}\nconst scalar = (v) => typeof v === \"string\" || typeof v === \"number\";\n/** A record's name: its first field (in the builder's order) holding a short text. */\nfunction nameOf(rec, own) {\n  for (const f of own) {\n    const t = typeof rec[f] === \"string\" ? clean(rec[f]) : \"\";\n    if (t && t.length <= 160) return t;\n  }\n  return \"\";\n}\n/**\n * Every record in a JSON value, outermost first: an object holding one of `fields` (one inside\n * another record's field is that record's own), with the names of the records around it.\n */\nfunction eachRecord(json, fields, visit) {\n  const walk = (v, around) => {\n    const x = unwrap(v);\n    if (Array.isArray(x)) {\n      for (const y of x) walk(y, around);\n      return;\n    }\n    if (!x || typeof x !== \"object\") return;\n    const own = fields.filter(\n      (f) => Object.prototype.hasOwnProperty.call(x, f) && x[f] != null && x[f] !== \"\",\n    );\n    const name = own.length ? nameOf(x, own) : \"\";\n    if (own.length) visit(x, own, name, around);\n    const inner = name ? [...around, name] : around;\n    for (const [k, y] of Object.entries(x)) if (!own.includes(k)) walk(y, inner);\n  };\n  walk(json, []);\n}\n/**\n * A field's value as the texts a visitor reads: itself, or inside it the values of the fields\n * listed (a class's teachers' names), else its texts (a list of tags).\n */\nfunction textsOf(v, fields) {\n  const x = unwrap(v);\n  if (scalar(x)) return [clean(String(x))].filter(Boolean);\n  const listed = [];\n  const any = [];\n  const walk = (y, k) => {\n    const z = unwrap(y);\n    if (scalar(z)) {\n      const t = clean(String(z));\n      if (!t) return;\n      if (fields.includes(k)) listed.push(t);\n      else if (typeof z === \"string\" && /\\p{L}/u.test(t) && !/^(https?:|\\/)|^[\\w-]{16,}$/.test(t)) any.push(t);\n      return;\n    }\n    if (Array.isArray(z)) for (const w of z) walk(w, k);\n    else if (z && typeof z === \"object\") for (const [kk, w] of Object.entries(z)) walk(w, kk);\n  };\n  walk(x, \"\");\n  return listed.length ? listed : any;\n}\n/** A data URL's records as a page: each record a section, its fields' values its lines. */\nfunction dataPage(url, json, read) {\n  const sections = [];\n  eachRecord(json, read.spec.fields, (rec, own, name, around) => {\n    const lines = [];\n    for (const f of own) {\n      if (typeof rec[f] === \"string\" && clean(rec[f]) === name) continue;\n      const texts = textsOf(rec[f], read.spec.fields);\n      if (!texts.length) continue;\n      // A short value reads with its field's name (\"level: Beginner\"); prose reads on its own.\n      if (texts.every((t) => t.split(\" \").length <= 8)) lines.push(`${f}: ${texts.join(\", \")}`);\n      else lines.push(...texts);\n    }\n    const heading = name || [...read.around, ...around].slice(-1)[0] || read.page || url;\n    sections.push({ name: heading.slice(0, 160), link: read.page, lines });\n  });\n  const name = read.around.length ? read.around.join(\" › \").slice(0, 160) : read.page || url;\n  // The words of its URL and its page's path (\"/api/classes\", \"/classes\"): what it is about,\n  // for the topics that route a visitor's words to it.\n  const words = `${read.spec.template.split(\"?\")[0].replace(PLACEHOLDER, \" \")} ${read.page || \"\"}`.replace(\n    /[/_.-]+/g,\n    \" \",\n  );\n  const chars = sections.reduce((n, s) => n + s.lines.join(\" \").length, 0);\n  return { path: url, name, title: \"\", words, description: \"\", sections, links: [], next: null, chars, data: true };\n}\n/** A data URL with its placeholders filled from `values` (each URL-encoded). */\nconst filled = (template, values) =>\n  template.replace(PLACEHOLDER, (_, k) => encodeURIComponent(String(values[k])));\n/** A URL's path segments, up to its first placeholder. */\nconst segments = (template) => template.split(/[?#{]/)[0].split(\"/\").filter(Boolean);\n/**\n * The data a URL's `{key}`s are filled from: the other listed data nearest it, sharing most of\n * its path (a class's `/api/classes/{id}` from the index `/api/classes`, not from\n * `/api/teachers`, whose records have ids too) — never its own.\n */\nfunction sourcesOf(spec) {\n  const mine = segments(spec.template);\n  const shared = (other) => {\n    const theirs = segments(other.template);\n    let n = 0;\n    while (n < mine.length && n < theirs.length && mine[n] === theirs[n]) n++;\n    return n;\n  };\n  const others = DATA.filter((d) => d !== spec);\n  const best = Math.max(0, ...others.map(shared));\n  return new Set(others.filter((d) => shared(d) === best));\n}\n\n/** Each data URL read this call, by URL: its JSON, what it was read for, and the names around it. */\nconst dataRead = new Map();\n/** Data URLs this call tried and could not read. */\nconst dataUnread = [];\n/**\n * Reads the site's data: the URLs listed, then, round by round, each URL whose `{key}`s the\n * records read so far fill (an index's ids → each item's data), FETCHES at once, within the\n * budget and DATA_MAX URLs. Each is fetched as the site sends it now (`no-store`), a GET.\n */\nasync function readData() {\n  const tried = new Set();\n  const fetchOne = async (job) => {\n    try {\n      const res = await fetch(job.url, {\n        credentials: \"same-origin\",\n        cache: \"no-store\",\n        headers: { accept: \"application/json\" },\n      });\n      if (!res.ok) throw new Error(`HTTP ${res.status}`);\n      // Data is JSON: a page, a file or anything else at a data URL is not read.\n      if (!/json/i.test(res.headers.get(\"content-type\") || \"\")) throw new Error(\"not JSON\");\n      dataRead.set(job.url, { spec: job.spec, json: await res.json(), around: job.around, page: job.page });\n    } catch {\n      dataUnread.push(job.url);\n    }\n  };\n  for (let round = 0; round <= DATA_ROUNDS && left() > 0; round++) {\n    const jobs = [];\n    for (const spec of DATA) {\n      const bindings = [];\n      if (!spec.keys.length) bindings.push({ values: {}, around: [] });\n      else {\n        // The records read so far, in the data nearest this URL, that hold every key: each\n        // fills the URL once.\n        const sources = sourcesOf(spec);\n        for (const r of dataRead.values()) {\n          if (!sources.has(r.spec)) continue;\n          // A key may be any of the record's own fields (its id), listed or not.\n          eachRecord(r.json, r.spec.fields, (rec, _own, _name, around) => {\n            if (spec.keys.every((k) => scalar(rec[k]) && String(rec[k]) !== \"\")) {\n              bindings.push({ values: rec, around: [...r.around, ...around] });\n            }\n          });\n        }\n      }\n      for (const b of bindings) {\n        const url = filled(spec.template, b.values);\n        if (tried.has(url) || tried.size >= DATA_MAX) continue;\n        // A URL a record filled in that names a change to the visitor's state is never read.\n        if (changeIn(url)) continue;\n        tried.add(url);\n        const pageKeys = spec.page ? [...spec.page.matchAll(PLACEHOLDER)].map((m) => m[1]) : [];\n        const page =\n          spec.page && pageKeys.every((k) => scalar(b.values[k])) ? filled(spec.page, b.values) : null;\n        jobs.push({ url, spec, around: [...new Set(b.around)].slice(-2), page });\n      }\n    }\n    if (!jobs.length) break;\n    const queue = [...jobs];\n    await Promise.all(\n      Array.from({ length: FETCHES }, async () => {\n        while (queue.length && left() > 0) await fetchOne(queue.shift());\n      }),\n    );\n    for (const j of queue) dataUnread.push(j.url);\n  }\n}\n\n/** Each page this call read, by the path it was asked for. */\nconst done = new Map();\n\n/**\n * Reads `paths` side by side — FETCHES fetched and FRAMES drawn at once, each lane taking the\n * next page in order as soon as it is free (a slow page holds one lane, not the others) —\n * until the budget runs out. The pages read, in the order asked.\n */\nasync function readAll(paths) {\n  const lane = async (queue) => {\n    while (queue.length && left() > 0) {\n      const path = queue.shift();\n      const page = await read(path);\n      if (page) done.set(path, page);\n    }\n  };\n  const fetched = paths.filter((p) => PAGES[p] !== \"frame\");\n  const drawn = paths.filter((p) => PAGES[p] === \"frame\");\n  await Promise.all([\n    ...Array.from({ length: FETCHES }, () => lane(fetched)),\n    ...Array.from({ length: FRAMES }, () => lane(drawn)),\n  ]);\n  return paths.map((p) => done.get(p)).filter(Boolean);\n}\n\n// ── Read: the page in view, then every page given — home, the plan's, the others listed ──\nconst here = location.pathname + location.search;\nconst pages = [];\nconst add = (list) => {\n  for (const p of list) if (p && !pages.some((q) => q.path === p.path)) pages.push(p);\n};\n/**\n * The page in view, once it has drawn its text: an app still saying only \"Loading\" as the\n * visitor asks (its route is being fetched) is waited for, a few seconds at most, while the\n * other pages are read, then read once it has gone quiet. One that never draws in time is read\n * as holding no text: \"Loading\" is not what the site says.\n */\nasync function readHere() {\n  const until = Date.now() + Math.min(5000, Math.max(0, left() - 2000));\n  let p = pageOf(document, here);\n  if (!blank(p)) return p;\n  while (blank(p) && Date.now() < until) {\n    await rt.sleep(250);\n    p = pageOf(document, here);\n  }\n  if (!blank(p)) {\n    await settle(document, window, Math.min(Date.now() + 2000, started + BUDGET_MS));\n    p = pageOf(document, here);\n  }\n  if (p && loading(p)) {\n    p.sections = [];\n    p.chars = 0;\n  }\n  return p;\n}\n/** Every page this call is given, in the order it reads them. */\nconst given = [...new Set([HOME, ...NAMED, ...Object.keys(PAGES)])].filter((p) => p !== here);\nconst [first, , inView] = await Promise.all([readAll(given), readData(), readHere()]);\nadd([inView]);\nadd(first);\n/** The site's data, read: each URL a page of records. */\nconst dataPages = [...dataRead].map(([url, r]) => dataPage(url, r.json, r));\nconst homePage =\n  (here === HOME ? pages[0] : first.find((p) => p.path === HOME)) || first[0] || pages[0];\n// A paginated index (a blog, a catalog) is read on: its next pages, a few at most.\nfor (let i = 0, from = first, room = MORE_PAGES; i < MORE && room > 0 && left() > 0; i++) {\n  const nexts = [\n    ...new Set(from.map((p) => p.next).filter((p) => p && !pages.some((q) => q.path === p))),\n  ].slice(0, room);\n  if (!nexts.length) break;\n  room -= nexts.length;\n  from = await readAll(nexts);\n  add(from);\n}\n/**\n * The pages given that were not read in time, or that held no text of their own (an app's\n * empty shell, a page that did not draw): named in the answer, so a page is never left out\n * without a word. Plain paths: they are not what the answer cites.\n */\nconst unread = [\n  ...given.filter((p) => !done.has(p) || done.get(p).chars === 0),\n  ...dataUnread,\n  ...dataPages.filter((p) => !p.sections.length).map((p) => p.path),\n];\n/** How many pages and data URLs the call was given. */\nconst givenCount = given.length + dataRead.size + dataUnread.length;\n/**\n * The answer, saying which pages it could not read when there are any: beside its entries as\n * `unread`, or, when it has none, in its message (a decline lists nothing).\n */\nconst answer = (out) => {\n  if (!unread.length) return out;\n  const note = `${unread.length} of the ${givenCount} pages it was given could not be read in time or held no text of their own`;\n  if (!out.items.length) {\n    const named = unread.slice(0, 10).join(\", \") + (unread.length > 10 ? \", …\" : \"\");\n    return { ...out, message: `${out.message} ${note}: ${named}.` };\n  }\n  return { ...out, unread, message: `${out.message ? `${out.message} ` : \"\"}${note} (unread).` };\n};\n\nif (!asked.length) {\n  // \"What is this site\": the home page's name and what it says the site is. Its description\n  // and its lines are apart on the page, so each ends as a sentence: an excerpt is read\n  // sentence by sentence, and none runs from one into the next.\n  const lines = homePage.sections.flatMap((s) => s.lines);\n  const all = [homePage.description, ...lines]\n    .map(clean)\n    .filter(Boolean)\n    .map((s) => (/[.!?]$/.test(s) ? s : `${s}.`))\n    .join(\" \");\n  const excerpt = all.length > 400 ? all.slice(0, all.lastIndexOf(\" \", 400)) : all;\n  return answer({\n    items: [{ name: homePage.name, excerpt: excerpt || homePage.name, path: homePage.path }],\n    count: 1,\n  });\n}\n\nif (left() > 0) {\n  const scored = new Map();\n  for (const p of pages) {\n    for (const l of p.links) {\n      if (pages.some((q) => q.path === l.path) || scored.has(l.path)) continue;\n      const stems = keyWords(l.text);\n      const f = flat(l.text);\n      const hits = asked.filter((w) => stems.some((x) => same(x, w)) || topicFor(w, f)).length;\n      if (hits) scored.set(l.path, hits);\n    }\n  }\n  const next = [...scored].sort((a, b) => b[1] - a[1]).slice(0, FOLLOW).map(([p]) => p);\n  add(await readAll(next));\n}\nadd(dataPages);\n\n// ── Rank: every sentence, by the question's words in it, in its headings, or its topics ──\n/**\n * Values a question asks for by kind (how much, how long, what time, which number): a\n * sentence holding one matches the word that asks for it — \"what does a wheel class cost\" is\n * answered by \"£40 a session\", which never says \"cost\".\n */\nconst KINDS = [\n  {\n    asks: /\\b(cost|costs|price|prices|priced|pricing|fee|fees|charge|charges|how much|cen(?:a|y|e|ie|ach)|koszt\\w*|preis\\w*|kost\\w*|prix|cout\\w*|tarif\\w*|precio\\w*|cuest\\w*|prezz\\w*|costo\\w*|preco\\w*|custo\\w*|prijs\\w*)\\b/,\n    words: [\"cost\", \"price\", \"pric\", \"fee\", \"charg\", \"cena\", \"koszt\", \"preis\", \"kost\", \"prix\", \"cout\", \"tarif\", \"precio\", \"cuest\", \"prezzo\", \"costo\", \"preco\", \"custo\", \"prijs\"],\n    value: /[$€£¥₹]\\s?\\d|\\d\\s?(?:€|£|zł|kr|chf|usd|eur|gbp|pln)\\b|\\bfree\\b/i,\n  },\n  {\n    asks: /\\b(how long|duration)\\b/,\n    words: [\"duration\"],\n    value: /\\b\\d+(?:[.,]\\d+)?\\s?(?:-\\s?\\d+\\s?)?(?:min(?:ute)?s?|h(?:ou)?rs?|days?|business days|weeks?|months?)\\b/i,\n  },\n  {\n    asks: /\\b(hours|open|opens|opening|close|closes|closing|what time|godzin\\w*|otwar\\w*|offnungszeit\\w*|geoffnet|horaire\\w*|ouvert\\w*|horario\\w*|abiert\\w*|orari\\w*|apert\\w*|abert\\w*|openingstijd\\w*)\\b/,\n    words: [\"hour\", \"open\", \"clos\", \"time\", \"godzin\", \"otwar\", \"offnungszeit\", \"geoffnet\", \"horaire\", \"ouvert\", \"horario\", \"abierto\", \"orari\", \"aperto\", \"aberto\", \"openingstijd\"],\n    value: /\\b\\d{1,2}(?::\\d{2})?\\s?(?:am|pm)\\b|\\b\\d{1,2}:\\d{2}\\b/i,\n  },\n  {\n    asks: /\\b(phone|telephone|call|telefon\\w*|telephon\\w*|telefono|telefone|numer|numeru|numerze)\\b/,\n    words: [\"phone\", \"telephone\", \"call\", \"number\", \"telefon\", \"telephon\", \"telefono\", \"telefone\", \"numer\"],\n    value: /(?:\\+|\\(\\d)?\\d[\\d\\s().-]{6,}\\d/,\n  },\n  {\n    asks: /\\b(e mail|email|mail)\\b/,\n    words: [\"email\", \"mail\"],\n    value: /[\\w.+-]+@[\\w-]+\\.[\\w.]+/,\n  },\n  {\n    // Who the visitor is signed in as: the account they are signed in to shows their address.\n    asks: /\\b(signed in|logged in|who am i|my account|my profile|zalogowan\\w*|angemeldet|eingeloggt|connecte|conectado|connesso|ingelogd)\\b/,\n    words: [\"sign\", \"logg\", \"account\", \"profil\", \"zalogowan\", \"angemeldet\", \"eingeloggt\", \"connect\", \"conectado\", \"connesso\", \"ingelogd\"],\n    value: /[\\w.+-]+@[\\w-]+\\.[\\w.]+/,\n  },\n  {\n    asks: /\\b(address|located|location|directions|adres\\w*|anschrift|direccion|indirizzo|endereco)\\b/,\n    words: [\"address\", \"locat\", \"adres\", \"anschrift\", \"direccion\", \"indirizzo\", \"endereco\"],\n    value:\n      /\\b\\d{1,5}[a-z]?\\s+(?:[A-Z][\\w'.-]*\\s+){0,3}(?:Street|St|Road|Rd|Avenue|Ave|Boulevard|Blvd|Lane|Ln|Drive|Dr|Way|Place|Court|Square|Highway)\\b|\\b(?:ul|al|rue|calle|via|avenida)\\.?\\s+[\\p{L}'.-]+(?:\\s+[\\p{L}'.-]+){0,3}\\s+\\d{1,5}\\b|[\\p{L}-]+(?:straße|strasse|str\\.|weg|gasse|platz)\\s+\\d{1,5}\\b/iu,\n  },\n].filter((k) => k.asks.test(tokens(question).join(\" \")));\n/** The kind whose value answers word `w` of the question, if any. */\nconst kindOf = (w) => KINDS.find((k) => k.words.some((x) => same(x, w)));\n/** Kinds asked in words that carry nothing else (\"how long\", \"what time\"): they only rank. */\nconst rankingKinds = KINDS.filter((k) => !asked.some((w) => kindOf(w) === k));\n\nconst units = [];\nfor (const page of pages) {\n  page.sections.forEach((s, k) => {\n    const sentences = [];\n    const lineOf = [];\n    s.lines.forEach((l, n) => {\n      for (const t of l.split(/(?<=[.!?])\\s+/).map(clean).filter(Boolean)) {\n        sentences.push(t);\n        lineOf.push(n);\n      }\n    });\n    // A sentence is read under its headings: its section's, its page's name and title.\n    const names = `${page.title || \"\"} ${page.words || \"\"} ${page.name} ${s.name}`;\n    const base = {\n      page,\n      s,\n      k,\n      sentences,\n      lineOf,\n      nameStems: keyWords(names),\n      nameFlat: flat(names),\n    };\n    // Values are looked for around the sentence (a label and its value, a table's row).\n    const near = (i) => s.lines.slice(Math.max(0, lineOf[i] - 2), lineOf[i] + 3).join(\" \");\n    (sentences.length ? sentences : [\"\"]).forEach((t, i) =>\n      units.push({ ...base, i, near: sentences.length ? near(i) : \"\", stems: keyWords(t), text: flat(t) }),\n    );\n  });\n}\nconst idf = (count) => Math.log(1 + units.length / (1 + count));\nconst inText = (u, w) => u.stems.some((x) => same(x, w));\nconst inNames = (u, w) => u.nameStems.some((x) => same(x, w));\nconst wordIdf = new Map(\n  asked.map((w) => [w, idf(units.filter((u) => inText(u, w)).length)]),\n);\nconst phraseIdf = new Map(\n  topics.map((t) => [t.phrase, idf(units.filter((u) => u.text.includes(t.phrase)).length)]),\n);\nconst kindIdf = new Map(KINDS.map((k) => [k, idf(units.filter((u) => k.value.test(u.near)).length)]));\n/**\n * A word in nearly every page's title (the site's own name) tells no page from another: an\n * answer need not hold it. It still ranks.\n */\nconst titled = pages.filter((p) => !p.data);\nconst titleWords = new Map(titled.map((p) => [p, keyWords(p.title || \"\")]));\nconst onPages = (w) => titled.filter((p) => titleWords.get(p).some((x) => same(x, w))).length;\nconst common = new Set(\n  titled.length >= 5 ? asked.filter((w) => onPages(w) >= Math.ceil(0.75 * titled.length)) : [],\n);\nconst counted = asked.filter((w) => !common.has(w));\nconst key = counted.length ? counted : asked;\n/** The words an answer must hold: most of what was asked, the site-wide words left out. */\nconst need = key.length <= 1 ? 1 : Math.floor(key.length / 2) + 1;\n\nconst best = new Map(); // one entry per section: its best sentence\nfor (const u of units) {\n  let hits = 0;\n  let score = 0;\n  for (const w of asked) {\n    // Where the word is: the sentence (or a topic routing it there), its headings, or — for a\n    // word asking for a kind of value — a value of that kind around the sentence. A word in\n    // both the sentence and its headings counts for both.\n    let weight = wordIdf.get(w);\n    let f = 0;\n    if (inText(u, w)) f += 2;\n    else {\n      const topic = topicFor(w, u.text, u.nameFlat);\n      if (topic) {\n        f += 2;\n        weight = Math.max(weight, phraseIdf.get(topic.phrase));\n      }\n    }\n    if (inNames(u, w)) f += 1;\n    if (!f) {\n      const kind = kindOf(w);\n      if (kind && kind.value.test(u.near)) f += 1;\n    }\n    if (!f) continue;\n    if (key.includes(w)) hits += 1;\n    score += weight * f;\n  }\n  if (hits < need) continue;\n  for (const k of rankingKinds) if (k.value.test(u.near)) score += kindIdf.get(k);\n  const at = `${u.page.path}#${u.k}`;\n  if (!best.has(at) || best.get(at).score < score) best.set(at, { u, score });\n}\nconst ranked = [...best.values()].sort((a, b) => b.score - a.score);\nconst lead = ranked.length ? ranked[0].score : 0; // the best score\n\n/**\n * The text around sentence `i`: its own block (a paragraph, a listing's card) and, when that\n * is short, the lines around it in its section (a table's row, a label and its value, a\n * question's answer), up to ~360 characters. Each line starts on its own (\"\\n\"): the answer reads\n * as the page does, while the check can find each line where the page has it.\n */\nfunction excerptOf(sentences, lineOf, i) {\n  if (i < 0 || i >= sentences.length) return \"\"; // a heading with no text under it\n  const at = sentences[i] || \"\";\n  if (at.length > 600) {\n    // A long run of text: the 600 characters around the first word asked, whole words only.\n    const hit = asked.map((w) => at.toLowerCase().indexOf(w)).filter((n) => n >= 0);\n    const from = Math.max(0, Math.min(...(hit.length ? hit : [0])) - 250);\n    const cut = at.slice(from, from + 600);\n    return cut.slice(from > 0 ? cut.indexOf(\" \") + 1 : 0, cut.lastIndexOf(\" \"));\n  }\n  const MAX = 360;\n  const inBlock = (k) => k >= 0 && k < sentences.length && lineOf[k] === lineOf[i];\n  const pick = [i];\n  let len = at.length;\n  for (let d = 1; len < MAX && (inBlock(i + d) || inBlock(i - d)); d++) {\n    if (inBlock(i + d)) {\n      pick.push(i + d);\n      len += sentences[i + d].length;\n    }\n    if (len < MAX && inBlock(i - d)) {\n      pick.unshift(i - d);\n      len += sentences[i - d].length;\n    }\n  }\n  // A short block: the whole lines after it, then before it, while they fit.\n  for (let fwd = true, stuck = 0; len < 200 && stuck < 2; fwd = !fwd) {\n    const k = fwd ? pick[pick.length - 1] + 1 : pick[0] - 1;\n    if (k < 0 || k >= sentences.length) {\n      stuck += 1;\n      continue;\n    }\n    const line = [];\n    for (let j = k; j >= 0 && j < sentences.length && lineOf[j] === lineOf[k]; j += fwd ? 1 : -1) line.push(j);\n    const add = line.reduce((n, j) => n + sentences[j].length, 0);\n    if (len + add > MAX) {\n      stuck += 1;\n      continue;\n    }\n    stuck = 0;\n    if (fwd) pick.push(...line);\n    else pick.unshift(...line.reverse());\n    len += add;\n  }\n  let out = \"\";\n  pick.forEach((k, n) => {\n    out += n === 0 ? sentences[k] : `${lineOf[k] === lineOf[pick[n - 1]] ? \" \" : \"\\n\"}${sentences[k]}`;\n  });\n  return out;\n}\n\n/** Where the answer links: its heading's link, or a link that is most of its own line. */\nfunction linkOf(u) {\n  const t = u.sentences[u.i] || \"\";\n  const l = u.page.links.find((x) => x.text.length >= 0.6 * t.length && t.includes(x.text));\n  return u.s.link || (l ? l.path : null);\n}\n\n/** The best entries, a few pages' worth: one page fills at most PER_PAGE of them. */\nconst perPage = new Map();\n/**\n * An entry for a page's own opening (its first section) on a page the question names by its\n * title (Classes, Workshops, a post): the page's sections follow its excerpt, as the page lists\n * them — what an index holds, or what an article covers.\n */\nfunction contentsOf(u, excerpt) {\n  if (u.k !== 0 && u.s.name !== u.page.name) return excerpt;\n  const titled = keyWords(u.page.name);\n  if (!key.some((w) => titled.some((x) => same(x, w)))) return excerpt;\n  const heads = [...new Set(u.page.sections.map((s) => s.name))].filter(\n    (n) => n && n !== u.page.name && !excerpt.includes(n),\n  );\n  let out = excerpt;\n  for (const h of heads) {\n    if (out.length + h.length + 3 > 480) break;\n    out += `\\n${h}`;\n  }\n  return out;\n}\nconst items = ranked\n  .filter((r) => r.score >= lead / 4)\n  .filter(({ u }) => {\n    const n = perPage.get(u.page.path) || 0;\n    perPage.set(u.page.path, n + 1);\n    return n < PER_PAGE;\n  })\n  .slice(0, TOP)\n  .map(({ u }) => ({\n    name: u.s.name === u.page.name ? u.s.name : `${u.s.name} — ${u.page.name}`,\n    excerpt: contentsOf(u, excerptOf(u.sentences, u.lineOf, u.i) || u.s.name),\n    path: u.page.path,\n    ...(linkOf(u) ? { link: linkOf(u) } : {}),\n  }));\nif (!items.length) {\n  const where = unread.length ? \"the pages read\" : \"this site's pages\";\n  return answer({ items: [], count: 0, message: `Nothing on ${where} answers \"${question}\".` });\n}\nreturn answer({ items, count: items.length });\n","mode":"imperative"},"annotations":{"readOnlyHint":true}},{"id":"611b5495-1fc6-484d-9b18-b0545ec09eaf","name":"get_product_details","description":"Returns a product’s name, TL price, gold karat and gram weight when shown, full description, specifications, any selectable options, availability, SKU and product URL. Use it when you need decision details for a specific product. The tool does not change the page.","input_schema":{"type":"object","required":["id"],"properties":{"id":{"type":"string","description":"Which product to read. Pass the product-page id (slug), its URL or path, or its name as shown on the site; for example, `dalgali-zigzag-formlu-elmas-kesim-kumlama-yuzeyli-kutu-kilitli-14-ayar-altin-kelepce-bilezik-klp0331`."}},"additionalProperties":false},"dependencies":[],"kind":"action","impl":{"code":"// scanner-v2 runtime 3 (harness/templates/_runtime) — agent-written tool below.\nconst template = {\"id\":\"agent\",\"version\":\"0\"};\nconst slots = {};\n// Runtime 3: the helpers every template stands on (scanner principle 4 — the model fills\n// slots; this tested runtime does the clicking, typing, waiting and reading). Plain browser\n// JavaScript with no imports. It is prepended to each template's tool (run by the Snippet\n// in the shopper's tab, where `document` and `location` may be the Snippet's shadows) and\n// to its check (run by the prover). Free variables: `template`, `slots`.\n// Never pass `document` or `window` themselves to a native API (they may be proxies):\n// use `document.documentElement`, and create events without a `view`.\n// Beside runtime 1 (NEK-1078): a URL's path placeholder also takes the item's own URL or\n// path (`resolveUrl`); a field spec may end `|slug` (an href's last path segment, the id\n// the item's page URL carries); `labelOf` reads the text just before an unlabelled group;\n// `ready`/`qReady` wait until a control is there and enabled (a framework re-renders it\n// after this script's turn); `pressEach` presses every match of a selector in turn.\n// Beside runtime 2 (NEK-1102): `findItem` opens an item by the name a visitor uses, found\n// the way a visitor finds it — on the site's own listing or search, from any page, read as\n// the server sends it or as the browser draws it — and `matchItem` is its matching;\n// `inFrame` reads a same-origin page as the browser draws it, in a hidden frame.\nconst rt = (() => {\n  const PLACEHOLDER = /\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g;\n  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n  const isSet = (v) => v !== undefined && v !== null && v !== \"\";\n\n  /** Lowercased, whitespace-collapsed text, for \"does the page show X\" comparisons. */\n  function norm(value) {\n    return String(value == null ? \"\" : value)\n      .replace(/\\s+/g, \" \")\n      .trim()\n      .toLowerCase();\n  }\n\n  /** Where a query ran, for error messages: a fetched page's path, else this page's. */\n  function where(root) {\n    const doc = root && (root.__rtUrl ? root : root.ownerDocument);\n    const url = doc && doc.__rtUrl ? doc.__rtUrl : location.href;\n    try {\n      const u = new URL(url);\n      return u.pathname + u.search;\n    } catch {\n      return String(url);\n    }\n  }\n\n  function slot(name) {\n    const value = slots[name];\n    if (!isSet(value)) throw new Error(`${template.id}: slot \"${name}\" is not set`);\n    return value;\n  }\n\n  function cssString(value) {\n    return String(value).replace(/[\"\\\\]/g, \"\\\\$&\").replace(/\\n/g, \"\\\\a \");\n  }\n\n  /** A selector with its {param} placeholders filled from `input` (CSS-string-escaped). */\n  function fill(selector, input) {\n    return String(selector).replace(PLACEHOLDER, (_, key) => {\n      const value = input ? input[key] : undefined;\n      if (!isSet(value)) throw new Error(`the selector ${selector} needs \"${key}\", which the call did not give`);\n      return cssString(value);\n    });\n  }\n\n  /** A selector slot, filled. */\n  function sel(name, input) {\n    return fill(slot(name), input);\n  }\n\n  /** The element a selector slot names; throws naming the slot when nothing matches. */\n  function q(name, input, root) {\n    const selector = sel(name, input);\n    const el = (root || document).querySelector(selector);\n    if (!el) throw new Error(`slot \"${name}\" (${selector}) matched nothing on ${where(root)}`);\n    return el;\n  }\n\n  /** The element a selector slot names, or null (also when the slot is not set). */\n  function qMaybe(name, input, root) {\n    return isSet(slots[name]) ? (root || document).querySelector(sel(name, input)) : null;\n  }\n\n  function qa(name, input, root) {\n    return [...(root || document).querySelectorAll(sel(name, input))];\n  }\n\n  /** Visible text of an element (rendered text on the live page, raw text elsewhere). */\n  function text(el) {\n    if (!el) return \"\";\n    const live = el.ownerDocument && el.ownerDocument.defaultView && el.isConnected;\n    const raw = live && typeof el.innerText === \"string\" ? el.innerText : el.textContent;\n    return String(raw || \"\").replace(/\\s+/g, \" \").trim();\n  }\n\n  /** What a control holds (a select's chosen option, an input's value), else its text. */\n  function valueOf(el) {\n    if (!el) return null;\n    if (el.tagName === \"SELECT\") {\n      const option = el.selectedOptions && el.selectedOptions[0];\n      return option ? option.value || text(option) : el.value;\n    }\n    if (el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\") return el.value;\n    return text(el);\n  }\n\n  function absolute(href, base) {\n    try {\n      return new URL(href, base || location.href).href;\n    } catch {\n      return href;\n    }\n  }\n\n  /** The last non-empty path segment of a URL or path (`/gb/products/t-shirt/` → `t-shirt`). */\n  function slug(value, base) {\n    if (!isSet(value)) return value;\n    let path = String(value).trim();\n    try {\n      path = new URL(path, base || location.href).pathname;\n    } catch {}\n    const parts = path.split(\"/\").filter(Boolean);\n    if (!parts.length) return String(value).trim();\n    try {\n      return decodeURIComponent(parts[parts.length - 1]);\n    } catch {\n      return parts[parts.length - 1];\n    }\n  }\n\n  /**\n   * One field of an item: `selector`, `selector@attr`, `@attr` or `.` (see the fields slot),\n   * each optionally ending `|slug`: the value's last path segment (an item's id from the\n   * link to its own page, `a@href|slug`).\n   */\n  function field(item, rawSpec, base) {\n    const piped = /\\|\\s*slug\\s*$/.exec(rawSpec);\n    if (piped) return slug(field(item, rawSpec.slice(0, piped.index).trim(), base), base);\n    const spec = rawSpec;\n    if (spec === \".\") return valueOf(item);\n    let selector = spec;\n    let attr = null;\n    const at = spec.lastIndexOf(\"@\");\n    if (at >= 0 && /^[A-Za-z_:][-A-Za-z0-9_:.]*$/.test(spec.slice(at + 1))) {\n      selector = spec.slice(0, at).trim();\n      attr = spec.slice(at + 1);\n    }\n    const el = selector ? item.querySelector(selector) : item;\n    if (!el) return null;\n    if (!attr) return valueOf(el);\n    const raw = el.getAttribute(attr);\n    if (raw === null) return null;\n    return attr === \"href\" || attr === \"src\" || attr === \"action\" ? absolute(raw, base) : raw.trim();\n  }\n\n  /** A number from text: \"$1,234.50\", \"£9.50\", \"1.234,50 €\", \"Qty 2\". Null when none. */\n  function number(value) {\n    if (value === null || value === undefined) return null;\n    if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n    const match = String(value).replace(/\\s/g, \"\").match(/-?\\d[\\d.,']*/);\n    if (!match) return null;\n    let s = match[0].replace(/'/g, \"\").replace(/[.,]$/, \"\");\n    const comma = s.lastIndexOf(\",\");\n    const dot = s.lastIndexOf(\".\");\n    if (comma > dot) {\n      const decimals = s.length - comma - 1;\n      s = dot === -1 && decimals === 3 ? s.replace(/,/g, \"\") : s.replace(/\\./g, \"\").replace(\",\", \".\");\n    } else {\n      s = s.replace(/,/g, \"\");\n    }\n    const n = Number(s);\n    return Number.isFinite(n) ? n : null;\n  }\n\n  /** Every number in a text (for \"the page shows this price\"). */\n  function numbers(value) {\n    return (String(value || \"\").match(/-?\\d[\\d.,']*\\d|\\d/g) || []).map(number).filter((n) => n !== null);\n  }\n\n  /** A time of day as HH:MM from \"9:00 AM\", \"2:30 pm\", \"14:30\". Null when it is not one. */\n  function clock(value) {\n    const m = /(\\d{1,2})[:.h](\\d{2})\\s*([ap])?\\.?\\s*m?\\.?/i.exec(String(value || \"\"));\n    if (!m) return null;\n    let hour = Number(m[1]);\n    const minute = Number(m[2]);\n    const half = m[3] ? m[3].toLowerCase() : \"\";\n    if (half === \"p\" && hour < 12) hour += 12;\n    if (half === \"a\" && hour === 12) hour = 0;\n    if (hour > 23 || minute > 59) return null;\n    return `${String(hour).padStart(2, \"0\")}:${String(minute).padStart(2, \"0\")}`;\n  }\n\n  function coerce(name, raw) {\n    if (name === \"price\" || name === \"subtotal\" || name === \"total\") return number(raw);\n    if (name === \"quantity\") {\n      const n = number(raw);\n      return n === null ? null : Math.round(n);\n    }\n    return raw;\n  }\n\n  /** Read the fields slot `fieldsSlot` from one element. Required fields that read nothing throw. */\n  function readFields(root, fieldsSlot, base, required) {\n    const specs = slot(fieldsSlot);\n    const out = {};\n    for (const [name, spec] of Object.entries(specs)) {\n      const raw = field(root, spec, base);\n      if ((raw === null || raw === \"\") && required && required.includes(name)) {\n        throw new Error(`slot \"${fieldsSlot}\" field \"${name}\" (${spec}) read nothing on ${where(root)}`);\n      }\n      out[name] = coerce(name, raw);\n      if ((name === \"price\" || name === \"subtotal\" || name === \"total\") && isSet(raw)) {\n        out[`${name}_text`] = String(raw).trim();\n      }\n    }\n    return out;\n  }\n\n  /** Read every item a selector slot matches, each through the fields slot. */\n  function readItems(root, itemSlot, fieldsSlot, input, base) {\n    return qa(itemSlot, input, root).map((item) => readFields(item, fieldsSlot, base));\n  }\n\n  /** Is this value an item's URL or site path rather than a bare id? */\n  function urlLike(value) {\n    return typeof value === \"string\" && /^(https?:\\/\\/|\\/)/i.test(value.trim());\n  }\n\n  /**\n   * The path placeholders' values a URL or path carries for this URL slot's path, or null\n   * when its path is not one the slot makes. Matched at the end of the path, so\n   * `/collections/all/products/mug` gives `{ id: \"mug\" }` for `/products/{id}`.\n   */\n  function pathValues(pathPart, value) {\n    let path;\n    try {\n      path = new URL(String(value).trim(), location.href).pathname;\n    } catch {\n      return null;\n    }\n    const keys = [];\n    const source = pathPart\n      .replace(/\\/+$/, \"\")\n      .split(PLACEHOLDER)\n      .map((part, i) => {\n        if (i % 2) {\n          keys.push(part);\n          return \"([^/]+)\";\n        }\n        return part.replace(/[.*+?^$()|[\\]{}\\\\]/g, \"\\\\$&\");\n      })\n      .join(\"\");\n    if (!keys.length) return null;\n    const m = new RegExp(`${source}/?$`).exec(path);\n    if (!m) return null;\n    const out = {};\n    keys.forEach((key, i) => {\n      try {\n        out[key] = decodeURIComponent(m[i + 1]);\n      } catch {\n        out[key] = m[i + 1];\n      }\n    });\n    return out;\n  }\n\n  /**\n   * A URL slot filled from `values` (then `defaults`), with the values it used: path\n   * placeholders must be given, as a bare value or as the item's own URL or path (whose\n   * path the slot's path matches); a query pair whose placeholder has no value is left out.\n   */\n  function resolveUrl(template, values, defaults) {\n    const raw = String(template);\n    const cut = raw.indexOf(\"?\");\n    const pathPart = cut < 0 ? raw : raw.slice(0, cut);\n    const queryPart = cut < 0 ? \"\" : raw.slice(cut + 1);\n    const given = { ...(values || {}) };\n    for (const [key, v] of Object.entries(given)) {\n      if (!urlLike(v) || !pathPart.includes(`{${key}}`)) continue;\n      const found = pathValues(pathPart, v);\n      if (!found) {\n        throw new Error(`\"${key}\" is ${v}, which is not a page ${pathPart} names: pass its id, or the URL of its own page`);\n      }\n      Object.assign(given, found);\n    }\n    const used = {};\n    const pick = (key) => {\n      const v = isSet(given[key]) ? given[key] : isSet(defaults && defaults[key]) ? defaults[key] : null;\n      if (v !== null) used[key] = String(v);\n      return v;\n    };\n    const path = pathPart.replace(PLACEHOLDER, (_, key) => {\n      const v = pick(key);\n      if (v === null) throw new Error(`the URL ${template} needs \"${key}\", which the call did not give`);\n      return encodeURIComponent(String(v));\n    });\n    const url = new URL(path, location.href);\n    for (const pair of queryPart.split(\"&\").filter(Boolean)) {\n      const eq = pair.indexOf(\"=\");\n      const key = decodeURIComponent(eq < 0 ? pair : pair.slice(0, eq));\n      let missing = false;\n      const value = (eq < 0 ? \"\" : pair.slice(eq + 1)).replace(PLACEHOLDER, (_, k) => {\n        const v = pick(k);\n        if (v === null) missing = true;\n        return v === null ? \"\" : String(v);\n      });\n      if (!missing) url.searchParams.append(key, value);\n    }\n    return { url: url.href, values: used };\n  }\n\n  /** A URL slot filled (see {@link resolveUrl}): the URL alone. */\n  function fillUrl(template, values, defaults) {\n    return resolveUrl(template, values, defaults).url;\n  }\n\n  /** Fetch a same-origin page as a document (the shopper's cookies go with it). */\n  async function fetchDoc(url) {\n    const res = await fetch(url, { credentials: \"same-origin\", headers: { accept: \"text/html\" } });\n    if (!res.ok) throw new Error(`${where({ __rtUrl: url })} answered HTTP ${res.status}`);\n    const doc = new DOMParser().parseFromString(await res.text(), \"text/html\");\n    doc.__rtUrl = res.url || url;\n    return doc;\n  }\n\n  /** Poll `check` until it answers truthy; throws `what` after `timeoutMs`. */\n  async function waitFor(check, what, timeoutMs) {\n    const limit = timeoutMs || 10000;\n    const started = Date.now();\n    for (;;) {\n      let value;\n      try {\n        value = await check();\n      } catch {\n        value = undefined;\n      }\n      if (value) return value;\n      if (Date.now() - started > limit) throw new Error(`${what} (waited ${Math.round(limit / 1000)} s on ${where()})`);\n      await sleep(50);\n    }\n  }\n\n  /** Resolve once the page has had no DOM change for `ms` (at most `maxMs`). */\n  function quiet(ms, maxMs) {\n    const calm = ms || 250;\n    return new Promise((resolve) => {\n      let timer;\n      let cap;\n      const observer = new MutationObserver(() => {\n        clearTimeout(timer);\n        timer = setTimeout(done, calm);\n      });\n      function done() {\n        observer.disconnect();\n        clearTimeout(timer);\n        clearTimeout(cap);\n        resolve();\n      }\n      observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });\n      timer = setTimeout(done, calm);\n      cap = setTimeout(done, maxMs || 5000);\n    });\n  }\n\n  /** The real click sequence a person's mouse makes: over, down, focus, up, click. */\n  function click(el) {\n    try {\n      el.scrollIntoView({ block: \"center\", inline: \"center\" });\n    } catch {}\n    const rect = el.getBoundingClientRect();\n    const at = { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 };\n    const base = { bubbles: true, cancelable: true, composed: true, button: 0, ...at };\n    const Pointer = typeof PointerEvent === \"function\" ? PointerEvent : MouseEvent;\n    const pointer = { ...base, pointerType: \"mouse\", isPrimary: true };\n    el.dispatchEvent(new Pointer(\"pointerover\", pointer));\n    el.dispatchEvent(new MouseEvent(\"mouseover\", base));\n    el.dispatchEvent(new Pointer(\"pointerdown\", { ...pointer, buttons: 1 }));\n    el.dispatchEvent(new MouseEvent(\"mousedown\", { ...base, buttons: 1 }));\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    el.dispatchEvent(new Pointer(\"pointerup\", pointer));\n    el.dispatchEvent(new MouseEvent(\"mouseup\", base));\n    el.click();\n  }\n\n  /** Is a control switched off (disabled, or aria-disabled)? */\n  function isDisabled(el) {\n    return Boolean(el.disabled) || el.getAttribute(\"aria-disabled\") === \"true\";\n  }\n\n  /**\n   * The control `find` returns (a function, or a selector on this page), once it is there\n   * and enabled: a framework draws a pick's effect after the script's turn (Add stays\n   * disabled until the size just chosen renders). After `timeoutMs` (5 s) it throws that\n   * `subject` matched nothing, or stays disabled, on `root`'s page (else this one).\n   */\n  async function ready(find, subject, timeoutMs, root) {\n    const get = typeof find === \"function\" ? find : () => document.querySelector(find);\n    const limit = timeoutMs || 5000;\n    const started = Date.now();\n    for (;;) {\n      let el = null;\n      try {\n        el = get();\n      } catch {}\n      if (el && el.isConnected && !isDisabled(el)) return el;\n      if (Date.now() - started > limit) {\n        const state = el && el.isConnected ? \"stays disabled\" : \"matched nothing\";\n        throw new Error(`${subject} ${state} on ${where(root)} (waited ${Math.round(limit / 1000)} s)`);\n      }\n      await sleep(50);\n    }\n  }\n\n  /** The element a selector slot names, once it is there and enabled. */\n  function qReady(name, input, root, timeoutMs) {\n    const selector = sel(name, input);\n    return ready(() => (root || document).querySelector(selector), `slot \"${name}\" (${selector})`, timeoutMs, root);\n  }\n\n  /**\n   * Press every element `selector` matches (on `root`, else this page), in page order, each\n   * once it is there and enabled, the page given a moment between presses — e.g. the first\n   * choice of each option group, before an Add button that needs them.\n   */\n  async function pressEach(selector, root, what) {\n    const scope = root || document;\n    const count = scope.querySelectorAll(selector).length;\n    if (!count) throw new Error(`${what}: ${selector} matched nothing on ${where(scope.documentElement || scope)}`);\n    for (let i = 0; i < count; i++) {\n      const el = await ready(() => scope.querySelectorAll(selector)[i], `${what}: match ${i + 1} of ${selector}`, 0, root);\n      click(el);\n      await sleep(150);\n    }\n    return count;\n  }\n\n  /**\n   * A check's seed: press `picks` (every match, see {@link pressEach}; none when null), then\n   * the add control `button` once it is enabled (both selectors, on `root`, else this page).\n   * A page still hydrating ignores the first presses, so picks that leave the button\n   * disabled are pressed again, twice at most. Throws a sentence naming the slots.\n   */\n  async function seed(picks, button, root, what) {\n    const scope = root || document;\n    const label = what || \"the seed\";\n    for (let round = 1; ; round++) {\n      if (picks) await pressEach(picks, scope, `${label}'s picks`);\n      try {\n        const el = await ready(() => scope.querySelector(button), \"\", 4000, root);\n        click(el);\n        return;\n      } catch {}\n      if (round >= 3) {\n        const there = scope.querySelector(button);\n        throw new Error(\n          !there\n            ? `${label}: its add control ${button} is not on ${where(scope.documentElement || scope)}`\n            : picks\n              ? `${label}: its add control ${button} stays disabled after pressing ${picks}`\n              : `${label}: its add control ${button} stays disabled; when adding needs a choice first (a size, a colour), name those controls in seed_picks`,\n        );\n      }\n    }\n  }\n\n  /** Set a control's value the way the page's framework sees a person do it. */\n  function setNative(el, value) {\n    const proto =\n      el.tagName === \"SELECT\"\n        ? HTMLSelectElement.prototype\n        : el.tagName === \"TEXTAREA\"\n          ? HTMLTextAreaElement.prototype\n          : HTMLInputElement.prototype;\n    const descriptor = Object.getOwnPropertyDescriptor(proto, \"value\");\n    if (descriptor && descriptor.set) descriptor.set.call(el, value);\n    else el.value = value;\n  }\n\n  function setValue(el, value) {\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    setNative(el, String(value));\n    el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"insertReplacementText\", data: String(value) }));\n    el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n  }\n\n  /** Type into a text box key by key (keydown, keypress, input, keyup), then change. */\n  async function type(el, value) {\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    setNative(el, \"\");\n    el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"deleteContentBackward\" }));\n    for (const ch of String(value)) {\n      const key = { key: ch, bubbles: true, cancelable: true };\n      el.dispatchEvent(new KeyboardEvent(\"keydown\", key));\n      el.dispatchEvent(new KeyboardEvent(\"keypress\", key));\n      setNative(el, el.value + ch);\n      el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"insertText\", data: ch }));\n      el.dispatchEvent(new KeyboardEvent(\"keyup\", key));\n      await sleep(5);\n    }\n    el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n  }\n\n  /** Press Enter in a box; like a browser, submit its form unless the page handled the key. */\n  function pressEnter(el) {\n    const init = { key: \"Enter\", code: \"Enter\", keyCode: 13, which: 13, bubbles: true, cancelable: true };\n    const unhandled = el.dispatchEvent(new KeyboardEvent(\"keydown\", init));\n    el.dispatchEvent(new KeyboardEvent(\"keypress\", init));\n    if (unhandled && el.form) {\n      if (typeof el.form.requestSubmit === \"function\") el.form.requestSubmit();\n      else el.form.submit();\n    }\n    el.dispatchEvent(new KeyboardEvent(\"keyup\", init));\n  }\n\n  /**\n   * The label a person reads for a control: its <label>, aria-label or aria-labelledby, a\n   * fieldset's legend, a wrapping label, its name — or, for a group drawn without any (a\n   * row of size buttons), the short text just before it (\"Select Size\" → \"Size\").\n   */\n  function labelOf(el) {\n    const doc = el.ownerDocument;\n    if (el.id && doc) {\n      const label = doc.querySelector(`label[for=\"${cssString(el.id)}\"]`);\n      if (label) return text(label);\n    }\n    const aria = el.getAttribute(\"aria-label\");\n    if (aria) return aria.trim();\n    const by = el.getAttribute(\"aria-labelledby\");\n    if (by && doc) {\n      const named = by\n        .split(/\\s+/)\n        .map((id) => text(doc.getElementById(id)))\n        .filter(Boolean)\n        .join(\" \");\n      if (named) return named;\n    }\n    const legend = el.tagName === \"FIELDSET\" ? el.querySelector(\"legend\") : null;\n    if (legend) return text(legend);\n    const wrap = el.closest(\"label\");\n    if (wrap && wrap !== el) return text(wrap);\n    if (el.getAttribute(\"name\")) return el.getAttribute(\"name\");\n    const before = el.previousElementSibling;\n    if (before && !before.querySelector(\"button, input, select, textarea, a\")) {\n      const said = text(before)\n        .replace(/^(select|choose|pick)\\s+(a\\s+|an\\s+|your\\s+)?/i, \"\")\n        .replace(/\\s*[:*]\\s*$/, \"\");\n      // A label is a few words (\"Size\"), not a price or a count beside the group.\n      if (said && said.length <= 40 && /[a-z]/i.test(said) && !/\\d/.test(said)) return said;\n    }\n    return \"\";\n  }\n\n  /** The choices of an option control: a select, a radio group, or a group of buttons. */\n  function choices(control) {\n    if (control.tagName === \"SELECT\") {\n      return [...control.options].map((o) => ({ label: text(o), value: o.value }));\n    }\n    const radios = [...control.querySelectorAll(\"input[type=radio], input[type=checkbox]\")];\n    if (radios.length) return radios.map((r) => ({ label: labelOf(r) || r.value, value: r.value, el: r }));\n    return [...control.querySelectorAll(\"button, [role=radio], [role=option]\")].map((b) => ({\n      label: text(b),\n      value: b.getAttribute(\"data-value\") || b.value || text(b),\n      el: b,\n    }));\n  }\n\n  /** An option control read as { name, values: [{ label, value }] }. */\n  function readOption(control) {\n    return { name: labelOf(control), values: choices(control).map(({ label, value }) => ({ label, value })) };\n  }\n\n  /** Pick `wanted` (a label or a value, any case) on an option control, as a person would. */\n  function choose(control, wanted, what) {\n    const want = norm(wanted);\n    const options = choices(control);\n    const hit = options.find((o) => norm(o.value) === want || norm(o.label) === want);\n    if (!hit) {\n      throw new Error(`${what}: no choice \"${wanted}\" (choices: ${options.map((o) => o.label).join(\", \")})`);\n    }\n    if (control.tagName === \"SELECT\") setValue(control, hit.value);\n    else click(hit.el);\n    return hit.label;\n  }\n\n  /** Where a link or a GET form's submit control goes; null for a POST form or no target. */\n  function controlTarget(el, base) {\n    const link = el.closest(\"a[href]\");\n    if (link) return absolute(link.getAttribute(\"href\"), base);\n    const form = el.form || el.closest(\"form\");\n    if (!form) return null;\n    const method = (el.getAttribute(\"formmethod\") || form.getAttribute(\"method\") || \"get\").toLowerCase();\n    if (method !== \"get\") return null;\n    const url = new URL(el.getAttribute(\"formaction\") || form.getAttribute(\"action\") || base, base);\n    url.search = \"\";\n    for (const control of form.elements) {\n      if (!control.name || control.disabled) continue;\n      const type = (control.type || \"\").toLowerCase();\n      if ([\"submit\", \"button\", \"image\", \"reset\", \"file\"].includes(type) && control !== el) continue;\n      if ((type === \"checkbox\" || type === \"radio\") && !control.checked) continue;\n      url.searchParams.append(control.name, control.value || \"\");\n    }\n    return url.href;\n  }\n\n  /** Go to `url` once the tool has returned (the Snippet defers a location change). */\n  function navigate(url) {\n    location.assign(url);\n  }\n\n  /** The live page's visible text, normalized. */\n  function pageText() {\n    return norm(document.body ? document.body.innerText : \"\");\n  }\n\n  /**\n   * A same-origin page's text as the site serves it now, normalized (fetched fresh; its\n   * scripts, styles and templates left out, so only what a person could read counts).\n   */\n  async function servedText(url) {\n    const doc = await fetchDoc(url);\n    if (!doc.body) return \"\";\n    doc.body.querySelectorAll(\"script, style, noscript, template\").forEach((el) => el.remove());\n    return norm(doc.body.textContent);\n  }\n\n  /** Does `path` match an SDK page pattern (`*` = any run of characters)? */\n  function matchPath(pattern, path) {\n    const escape = (part) => part.replace(/[.+?^$()|[\\]{}\\\\]/g, \"\\\\$&\");\n    const source = String(pattern).split(\"*\").map(escape).join(\".*\");\n    return new RegExp(\"^\" + source + \"$\").test(path);\n  }\n\n  /** A form field a person has typed into (hidden fields and buttons don't count). */\n  function isTyped(field) {\n    const type = (field.type || \"text\").toLowerCase();\n    if ([\"hidden\", \"submit\", \"button\", \"image\", \"reset\", \"checkbox\", \"radio\"].includes(type)) return false;\n    if (field.tagName === \"SELECT\") return false;\n    return isSet(field.value);\n  }\n\n  // ── An item by the name a visitor uses (NEK-1102) ──\n\n  /** Text as names compare: accents, case, apostrophes, punctuation and spacing aside. */\n  function fold(value) {\n    return String(value == null ? \"\" : value)\n      .normalize(\"NFD\")\n      .replace(/\\p{M}+/gu, \"\")\n      .toLowerCase()\n      .replace(/['’‘`]/g, \"\")\n      .replace(/[^\\p{L}\\p{N}]+/gu, \" \")\n      .trim();\n  }\n\n  /** An element's text with a space between its pieces: \"2021\" then \"Harbour Blend\" is two words. */\n  function spaced(el) {\n    if (!el) return \"\";\n    const parts = [];\n    const walk = (node) => {\n      for (const child of node.childNodes) {\n        if (child.nodeType === 3) parts.push(child.nodeValue);\n        else if (child.nodeType === 1 && !/^(script|style|noscript|template|svg)$/i.test(child.tagName)) walk(child);\n      }\n    };\n    walk(el);\n    return parts.join(\" \").replace(/\\s+/g, \" \").trim();\n  }\n\n  /** A URL's or path's path, without its query, hash or trailing slash (null when not one). */\n  function pathOf(url, base) {\n    try {\n      return new URL(String(url), base || location.href).pathname.replace(/\\/+$/, \"\") || \"/\";\n    } catch {\n      return null;\n    }\n  }\n\n  /**\n   * Does `path` match a page pattern? `*` or a `{name}` placeholder is one path segment, `**`\n   * any depth: `/shop/*` is an item's page, never `/shop/a/b`.\n   */\n  function isPage(pattern, path) {\n    const source = String(pattern)\n      .replace(/^https?:\\/\\/[^/]+/i, \"\")\n      .split(/[?#]/)[0]\n      .replace(/\\/+$/, \"\")\n      .split(/(\\*\\*|\\*|\\{[A-Za-z_][A-Za-z0-9_]*\\})/)\n      .map((part, i) => (i % 2 ? (part === \"**\" ? \".*\" : \"[^/]+\") : part.replace(/[.+?^$()|[\\]{}\\\\]/g, \"\\\\$&\")))\n      .join(\"\");\n    return new RegExp(`^${source || \"/\"}$`).test(String(path).replace(/\\/+$/, \"\") || \"/\");\n  }\n\n  const HEADING = \"h1, h2, h3, h4, h5, h6, [role=heading]\";\n\n  /**\n   * The items a page links to: one entry per same-origin path matching `link`, with every name\n   * the page gives it (a heading in the link, else the heading of the card the link sits in,\n   * its label or title, its text, an image's alt) and its path's last segment (`id`).\n   */\n  function itemLinks(root, link, base) {\n    const at = base || (root && root.__rtUrl) || location.href;\n    const origin = new URL(at, location.href).origin;\n    const byPath = new Map();\n    const anchors = [...root.querySelectorAll(\"a[href]\")];\n    const pathOfLink = (a) => {\n      try {\n        const url = new URL(a.getAttribute(\"href\"), at);\n        return url.origin === origin ? url.pathname.replace(/\\/+$/, \"\") || \"/\" : null;\n      } catch {\n        return null;\n      }\n    };\n    for (const a of anchors) {\n      const path = pathOfLink(a);\n      if (!path || !isPage(link, path)) continue;\n      let entry = byPath.get(path);\n      if (!entry) {\n        entry = { id: slug(path), path, url: origin + path, name: \"\", names: [] };\n        byPath.set(path, entry);\n      }\n      const add = (value) => {\n        const t = String(value || \"\").replace(/\\s+/g, \" \").trim();\n        if (t && t.length <= 300 && /[\\p{L}\\p{N}]/u.test(t) && !entry.names.includes(t)) entry.names.push(t);\n      };\n      const heads = [...a.querySelectorAll(HEADING)];\n      for (const h of heads) add(spaced(h));\n      if (!heads.length) {\n        // A link whose text is not the name (\"Read more\", a picture): its card's heading, when\n        // the card links to no other item.\n        let card = a.parentElement;\n        for (let up = 0; card && up < 4; up += 1, card = card.parentElement) {\n          const other = [...card.querySelectorAll(\"a[href]\")].some((b) => {\n            const p = pathOfLink(b);\n            return p && p !== path && isPage(link, p);\n          });\n          if (other) break;\n          const h = card.querySelector(HEADING);\n          if (h) {\n            add(spaced(h));\n            break;\n          }\n        }\n      }\n      add(a.getAttribute(\"aria-label\"));\n      add(a.getAttribute(\"title\"));\n      add(spaced(a));\n      for (const img of a.querySelectorAll(\"img[alt]\")) add(img.getAttribute(\"alt\"));\n    }\n    for (const entry of byPath.values()) entry.name = entry.names[0] || entry.id;\n    return [...byPath.values()];\n  }\n\n  /** Does one of an entry's names (or its id, in words) hold every word of `words`? */\n  function holds(entry, words) {\n    return [...entry.names, entry.id].some((n) => {\n      const have = new Set(fold(n).split(\" \"));\n      return words.every((w) => have.has(w));\n    });\n  }\n\n  /** How close an entry's names come to `words`: whole words shared, then words begun alike. */\n  function closeness(entry, words) {\n    let best = 0;\n    for (const n of [...entry.names, entry.id]) {\n      const have = fold(n).split(\" \").filter(Boolean);\n      let score = 0;\n      for (const w of words) {\n        if (have.includes(w)) score += 1;\n        else if (w.length >= 3 && have.some((h) => h.length >= 3 && (h.startsWith(w) || w.startsWith(h)))) score += 0.5;\n      }\n      best = Math.max(best, score);\n    }\n    return best;\n  }\n\n  /**\n   * The one entry (as `itemLinks` gives them) a visitor's name picks: the one one of whose\n   * names is the name (case, accents and punctuation aside), else the one whose name holds\n   * every word of it (\"Harbour Blend\" finds \"2021 Harbour Blend Coffee\"), never the closest\n   * guess. More than one, or none, throws a plain error naming the closest with their ids.\n   */\n  function matchItem(name, entries, what) {\n    const noun = what || \"item\";\n    const list = entries || [];\n    const wanted = fold(name);\n    const words = wanted.split(\" \").filter(Boolean);\n    if (!words.length) throw new Error(`name the ${noun}: its name as the site shows it, its id, or its page's URL`);\n    const named = (e) => `\"${e.name}\"${e.parent ? ` in \"${e.parent.name}\"` : \"\"} (id ${e.id})`;\n    const exact = list.filter((e) => e.names.some((n) => fold(n) === wanted) || fold(e.id) === wanted);\n    if (exact.length === 1) return exact[0];\n    const holding = exact.length ? exact : list.filter((e) => holds(e, words));\n    if (holding.length === 1) return holding[0];\n    if (holding.length > 1) {\n      const more = holding.length > 6 ? \", …\" : \"\";\n      throw new Error(\n        `\"${name}\" names ${holding.length} ${noun}s here: ${holding.slice(0, 6).map(named).join(\", \")}${more}. Pass one's full name or id.`,\n      );\n    }\n    if (!list.length) throw new Error(`no ${noun} is named \"${name}\": the site lists no ${noun}s where it was looked for`);\n    const closest = list\n      .map((e) => ({ e, score: closeness(e, words) }))\n      .filter((x) => x.score > 0)\n      .sort((a, b) => b.score - a.score)\n      .slice(0, 3)\n      .map((x) => x.e);\n    const shown = closest.length\n      ? `The closest: ${closest.map(named).join(\", \")}.`\n      : `It lists ${list.slice(0, 3).map(named).join(\", \")}${list.length > 3 ? ` and ${list.length - 3} more` : \"\"}.`;\n    throw new Error(`No ${noun} is named \"${name}\" on this site. ${shown}`);\n  }\n\n  /**\n   * A same-origin page as the browser draws it: loaded in a hidden frame, `read(doc)` once\n   * `ready(doc)` holds (or, when `ms` — 15 s by default — runs out, the page as it is by\n   * then), the frame removed after. Throws when the page does not open in a frame at all (a\n   * site that refuses to be framed).\n   */\n  async function inFrame(url, ready, read, ms) {\n    const frame = document.createElement(\"iframe\");\n    frame.setAttribute(\"aria-hidden\", \"true\");\n    frame.tabIndex = -1;\n    frame.style.cssText =\n      \"position:fixed;left:-12000px;top:0;width:1280px;height:900px;border:0;visibility:hidden;pointer-events:none\";\n    frame.src = url;\n    (document.body || document.documentElement).append(frame);\n    const limit = ms || 15000;\n    const started = Date.now();\n    try {\n      for (;;) {\n        let doc = null;\n        try {\n          doc = frame.contentDocument;\n        } catch {}\n        const loaded = Boolean(doc && doc.body && doc.readyState !== \"loading\" && doc.location.href !== \"about:blank\");\n        let done = false;\n        if (loaded) {\n          doc.__rtUrl = doc.location.href;\n          try {\n            done = !ready || Boolean(ready(doc));\n          } catch {}\n        }\n        if (done || (loaded && Date.now() - started > limit)) return await read(doc);\n        if (Date.now() - started > limit) {\n          throw new Error(`${where({ __rtUrl: url })} did not open in a hidden frame within ${Math.round(limit / 1000)} s (the site may refuse to be framed)`);\n        }\n        await sleep(100);\n      }\n    } finally {\n      frame.remove();\n    }\n  }\n\n  /**\n   * The item a caller names, found the way a visitor finds it (NEK-1102). `name` is its name\n   * or title as the site shows it, or the shorter one a person uses (\"Harbour Blend\" for\n   * \"2021 Harbour Blend Coffee\"), its id, or its page's URL or path. `where`:\n   * - `link` (required): the item pages' pattern, `*` one path segment, `**` any depth\n   *   (`/products/*`);\n   * - `list`: the page or pages that link the items — a listing, or a search whose URL takes\n   *   the name as `{query}` (`/search?q={query}`); `/` by default;\n   * - `page`: the item page's URL with `{id}` (`/products/{id}`): an id the listing does not\n   *   show opens there, when the site has that page;\n   * - `via`: the pattern of the pages that list the items themselves when `list` links only\n   *   to those (a course's page listing its lessons): read when `list` names none;\n   * - `what`: the item's noun, for the errors (`\"product\"`, `\"lesson\"`);\n   * - `ms`: how long it may look (30 s by default; `max_pages` via-pages at most, 12).\n   * A URL or path opens directly. Each page is read as the server sends it, or — when script\n   * draws its links — as the browser draws it (`inFrame`). Returns `{ id, name, path, url }`,\n   * with `parent` (`{ id, name, path, url }`) for an item found via one. A name that answers\n   * to no item or several throws a plain error naming the closest items with their ids\n   * (`matchItem`).\n   */\n  async function findItem(name, where_) {\n    const opts = where_ || {};\n    if (!isSet(opts.link)) throw new Error(\"findItem needs `link`: the item pages' pattern, e.g. /products/*\");\n    const noun = opts.what || \"item\";\n    const raw = String(name == null ? \"\" : name).trim();\n    if (!raw) throw new Error(`name the ${noun}: its name as the site shows it, its id, or its page's URL`);\n    const deadline = Date.now() + (opts.ms || 30000);\n    const left = () => deadline - Date.now();\n    const found = (e) => ({\n      id: e.id,\n      name: e.name || null,\n      path: e.path,\n      url: e.url,\n      ...(e.parent ? { parent: { id: e.parent.id, name: e.parent.name, path: e.parent.path, url: e.parent.url } } : {}),\n    });\n    // Its own page's URL or path.\n    if (urlLike(raw)) {\n      let url = null;\n      try {\n        url = new URL(raw, location.href);\n      } catch {}\n      const path = url && url.origin === location.origin ? pathOf(url.href) : null;\n      if (path && (isPage(opts.link, path) || (opts.page && isPage(opts.page, path)))) {\n        return { id: slug(path), name: null, path, url: location.origin + path };\n      }\n      throw new Error(`${raw} is not a ${noun}'s page on this site (${opts.link}): pass its name, its id, or its page's URL`);\n    }\n    // Its name or id, where the site lists it.\n    const entries = new Map();\n    const parents = new Map();\n    const take = (doc, base, parent) => {\n      for (const e of itemLinks(doc, opts.link, base)) {\n        const had = entries.get(e.path);\n        if (had) {\n          for (const n of e.names) if (!had.names.includes(n)) had.names.push(n);\n        } else entries.set(e.path, parent ? { ...e, parent } : e);\n      }\n      if (opts.via && !parent) {\n        for (const e of itemLinks(doc, opts.via, base)) if (!parents.has(e.path) && !entries.has(e.path)) parents.set(e.path, e);\n      }\n    };\n    const has = (doc, withVia) =>\n      itemLinks(doc, opts.link, doc.__rtUrl).length > 0 || (withVia && itemLinks(doc, opts.via, doc.__rtUrl).length > 0);\n    // A page's links as the server sends them, else as the browser draws them.\n    const read = async (url, parent, ms) => {\n      let doc = null;\n      try {\n        doc = await fetchDoc(url);\n      } catch {}\n      if (doc && has(doc, !parent && opts.via)) return take(doc, doc.__rtUrl, parent);\n      if (left() < 500) return doc ? take(doc, doc.__rtUrl, parent) : undefined;\n      try {\n        await inFrame(url, (d) => has(d, !parent && opts.via), (d) => take(d, d.__rtUrl, parent), Math.min(ms, left()));\n      } catch {\n        if (doc) take(doc, doc.__rtUrl, parent);\n      }\n    };\n    for (const list of [].concat(opts.list || \"/\")) {\n      const url = new URL(String(list).replace(/\\{query\\}/g, encodeURIComponent(raw)), location.href).href;\n      await read(url, null, 15000);\n    }\n    const words = fold(raw).split(\" \").filter(Boolean);\n    const any = () => [...entries.values()].some((e) => fold(e.id) === fold(raw) || holds(e, words));\n    if (opts.via && parents.size && !any()) {\n      // Parts inside items: read every item page that lists them, a few at a time (a part's\n      // name may repeat in another item: the error then names both).\n      const queue = [...parents.values()].slice(0, opts.max_pages || 12);\n      const worker = async () => {\n        while (queue.length && left() > 500) {\n          const parent = queue.shift();\n          await read(parent.url, parent, 10000);\n        }\n      };\n      await Promise.all([worker(), worker(), worker()]);\n    }\n    // An id no listing shows (a later page of it, an item it leaves out) opens on its own page\n    // when the site has one.\n    if (!any() && opts.page && !/\\s/.test(raw)) {\n      const url = new URL(String(opts.page).replace(PLACEHOLDER, () => encodeURIComponent(raw)), location.href);\n      try {\n        const res = await fetch(url.href, { credentials: \"same-origin\", headers: { accept: \"text/html\" } });\n        if (res.ok) {\n          const path = pathOf(url.href);\n          return { id: raw, name: null, path, url: location.origin + path };\n        }\n      } catch {}\n    }\n    return found(matchItem(raw, [...entries.values()], noun));\n  }\n\n  return {\n    sleep, norm, where, slot, fill, sel, q, qMaybe, qa, text, valueOf, field, slug, number,\n    numbers, clock, readFields, readItems, urlLike, resolveUrl, fillUrl, fetchDoc, waitFor,\n    quiet, click, isDisabled, ready, qReady, pressEach, seed, setValue, type, pressEnter, labelOf,\n    readOption, choose, controlTarget, navigate, pageText, servedText, matchPath, isTyped,\n    fold, isPage, itemLinks, matchItem, inFrame, findItem,\n  };\n})();\nconst raw = String(input.id == null ? \"\" : input.id).trim();\nif (!raw) throw new Error(\"Name a product by its product-page id, URL, path, or name.\");\nconst item = await rt.findItem(raw, {\n  link: \"/urun/*\",\n  list: \"/\",\n  page: \"/urun/{id}\",\n  what: \"product\",\n});\nconst target = new URL(item.url, location.href);\nif (target.origin !== location.origin) throw new Error(\"The product page must be on this site.\");\nconst current = new URL(location.href);\nconst doc = current.pathname === target.pathname ? document : await rt.fetchDoc(target.href);\nconst h1 = doc.querySelector(\"h1.urun-ad\") || doc.querySelector(\"main h1\");\nif (!h1) throw new Error(`Could not find product details on ${item.path}.`);\nconst name = rt.text(h1);\nconst priceEl = doc.querySelector(\".urun-fiyat__tutar\");\nconst priceText = priceEl ? rt.text(priceEl) : \"\";\nconst price = rt.number(priceText);\nif (!(price > 0)) throw new Error(`The product page does not show a valid TL price for ${name}.`);\n\nconst stamps = doc.querySelector(\".urun-damga\");\nconst stampText = stamps ? rt.text(stamps) : \"\";\nconst karatMatch = stampText.match(/(\\d+)\\s*Ayar/i);\nconst weightMatch = stampText.match(/(\\d+(?:[.,]\\d+)?)\\s*gram/i);\nconst karat = karatMatch ? Number(karatMatch[1]) : null;\nconst weightGrams = weightMatch ? rt.number(weightMatch[1]) : null;\nconst tolerance = stamps?.querySelector(\".urun-damga--gram em\") ? rt.text(stamps.querySelector(\".urun-damga--gram em\")) : undefined;\nconst karatGram = karat !== null && weightGrams !== null\n  ? `${karat} · ${weightGrams.toFixed(2)} gr`\n  : undefined;\n\nconst descriptionRoot = doc.querySelector(\"#content-description\");\nconst description = descriptionRoot ? rt.text(descriptionRoot) : undefined;\nconst detailsRoot = h1.parentElement;\nconst optionControls = detailsRoot\n  ? [...detailsRoot.querySelectorAll(\"select, fieldset, [role='radiogroup'], [data-option-group]\")]\n      .filter((el) => el.querySelector(\"option, input[type='radio'], input[type='checkbox'], button, [role='radio'], [role='option']\"))\n  : [];\nconst options = optionControls.map((control) => rt.readOption(control));\nconst attributes = {};\nfor (const row of doc.querySelectorAll(\"#content-specifications .ub-satir\")) {\n  const key = rt.text(row.querySelector(\"dt\"));\n  const value = rt.text(row.querySelector(\"dd\"));\n  if (key && value) attributes[key] = value;\n}\nfor (const row of detailsRoot?.querySelectorAll(\".grid.grid-cols-2 > div\") || []) {\n  const parts = [...row.querySelectorAll(\":scope > div > div\")].map(rt.text).filter(Boolean);\n  if (parts.length >= 2) attributes[parts[0]] = parts[1];\n}\nconst scripts = [...doc.querySelectorAll('script[type=\"application/ld+json\"]')];\nlet productData = null;\nfor (const script of scripts) {\n  try {\n    const parsed = JSON.parse(script.textContent || \"null\");\n    const nodes = Array.isArray(parsed) ? parsed : [parsed];\n    productData = nodes.find((node) => String(node?.['@type'] || \"\").split(/\\s+/).includes(\"Product\")) || productData;\n  } catch {}\n}\nconst offer = Array.isArray(productData?.offers) ? productData.offers[0] : productData?.offers;\nconst schemaAvailability = String(offer?.availability || \"\").split(/[\\/#]/).pop();\nlet availability;\nif (/InStock/i.test(schemaAvailability)) availability = \"In stock\";\nelse if (/OutOfStock|SoldOut/i.test(schemaAvailability)) availability = \"Out of stock\";\nelse if (/PreOrder/i.test(schemaAvailability)) availability = \"Pre-order\";\nelse if (/BackOrder/i.test(schemaAvailability)) availability = \"Backorder\";\nelse {\n  const addButton = doc.querySelector(\"button.add-cart.urun-sepet\");\n  if (addButton && !addButton.disabled) availability = \"Available to add to cart\";\n}\n\nconst sku = rt.text(doc.querySelector(\".urun-damga--kod\")) || productData?.sku;\nreturn {\n  id: item.id,\n  name,\n  price,\n  price_text: priceText,\n  ...(karat !== null ? { karat } : {}),\n  ...(weightGrams !== null ? { weight_grams: weightGrams } : {}),\n  ...(karatGram ? { karat_gram: karatGram } : {}),\n  ...(tolerance ? { weight_tolerance: tolerance } : {}),\n  ...(description ? { description } : {}),\n  options,\n  ...(Object.keys(attributes).length ? { attributes } : {}),\n  ...(availability ? { availability } : {}),\n  ...(sku ? { sku } : {}),\n  url: item.url,\n};\n","mode":"imperative"},"annotations":{"readOnlyHint":true},"page":"/urun/*"},{"id":"2a221408-04f4-42d9-8b14-d087ad6a8bce","name":"start_checkout","description":"Open the cart's checkout and return the checkout path, page heading, delivery-details heading, cart lines, and displayed total. Stops at the details step; it does not fill shopper information or submit an order.","input_schema":{"type":"object","properties":{},"additionalProperties":false},"dependencies":[],"kind":"action","impl":{"code":"// scanner-v2 runtime 3 (harness/templates/_runtime) — agent-written tool below.\nconst template = {\"id\":\"agent\",\"version\":\"0\"};\nconst slots = {};\n// Runtime 3: the helpers every template stands on (scanner principle 4 — the model fills\n// slots; this tested runtime does the clicking, typing, waiting and reading). Plain browser\n// JavaScript with no imports. It is prepended to each template's tool (run by the Snippet\n// in the shopper's tab, where `document` and `location` may be the Snippet's shadows) and\n// to its check (run by the prover). Free variables: `template`, `slots`.\n// Never pass `document` or `window` themselves to a native API (they may be proxies):\n// use `document.documentElement`, and create events without a `view`.\n// Beside runtime 1 (NEK-1078): a URL's path placeholder also takes the item's own URL or\n// path (`resolveUrl`); a field spec may end `|slug` (an href's last path segment, the id\n// the item's page URL carries); `labelOf` reads the text just before an unlabelled group;\n// `ready`/`qReady` wait until a control is there and enabled (a framework re-renders it\n// after this script's turn); `pressEach` presses every match of a selector in turn.\n// Beside runtime 2 (NEK-1102): `findItem` opens an item by the name a visitor uses, found\n// the way a visitor finds it — on the site's own listing or search, from any page, read as\n// the server sends it or as the browser draws it — and `matchItem` is its matching;\n// `inFrame` reads a same-origin page as the browser draws it, in a hidden frame.\nconst rt = (() => {\n  const PLACEHOLDER = /\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g;\n  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n  const isSet = (v) => v !== undefined && v !== null && v !== \"\";\n\n  /** Lowercased, whitespace-collapsed text, for \"does the page show X\" comparisons. */\n  function norm(value) {\n    return String(value == null ? \"\" : value)\n      .replace(/\\s+/g, \" \")\n      .trim()\n      .toLowerCase();\n  }\n\n  /** Where a query ran, for error messages: a fetched page's path, else this page's. */\n  function where(root) {\n    const doc = root && (root.__rtUrl ? root : root.ownerDocument);\n    const url = doc && doc.__rtUrl ? doc.__rtUrl : location.href;\n    try {\n      const u = new URL(url);\n      return u.pathname + u.search;\n    } catch {\n      return String(url);\n    }\n  }\n\n  function slot(name) {\n    const value = slots[name];\n    if (!isSet(value)) throw new Error(`${template.id}: slot \"${name}\" is not set`);\n    return value;\n  }\n\n  function cssString(value) {\n    return String(value).replace(/[\"\\\\]/g, \"\\\\$&\").replace(/\\n/g, \"\\\\a \");\n  }\n\n  /** A selector with its {param} placeholders filled from `input` (CSS-string-escaped). */\n  function fill(selector, input) {\n    return String(selector).replace(PLACEHOLDER, (_, key) => {\n      const value = input ? input[key] : undefined;\n      if (!isSet(value)) throw new Error(`the selector ${selector} needs \"${key}\", which the call did not give`);\n      return cssString(value);\n    });\n  }\n\n  /** A selector slot, filled. */\n  function sel(name, input) {\n    return fill(slot(name), input);\n  }\n\n  /** The element a selector slot names; throws naming the slot when nothing matches. */\n  function q(name, input, root) {\n    const selector = sel(name, input);\n    const el = (root || document).querySelector(selector);\n    if (!el) throw new Error(`slot \"${name}\" (${selector}) matched nothing on ${where(root)}`);\n    return el;\n  }\n\n  /** The element a selector slot names, or null (also when the slot is not set). */\n  function qMaybe(name, input, root) {\n    return isSet(slots[name]) ? (root || document).querySelector(sel(name, input)) : null;\n  }\n\n  function qa(name, input, root) {\n    return [...(root || document).querySelectorAll(sel(name, input))];\n  }\n\n  /** Visible text of an element (rendered text on the live page, raw text elsewhere). */\n  function text(el) {\n    if (!el) return \"\";\n    const live = el.ownerDocument && el.ownerDocument.defaultView && el.isConnected;\n    const raw = live && typeof el.innerText === \"string\" ? el.innerText : el.textContent;\n    return String(raw || \"\").replace(/\\s+/g, \" \").trim();\n  }\n\n  /** What a control holds (a select's chosen option, an input's value), else its text. */\n  function valueOf(el) {\n    if (!el) return null;\n    if (el.tagName === \"SELECT\") {\n      const option = el.selectedOptions && el.selectedOptions[0];\n      return option ? option.value || text(option) : el.value;\n    }\n    if (el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\") return el.value;\n    return text(el);\n  }\n\n  function absolute(href, base) {\n    try {\n      return new URL(href, base || location.href).href;\n    } catch {\n      return href;\n    }\n  }\n\n  /** The last non-empty path segment of a URL or path (`/gb/products/t-shirt/` → `t-shirt`). */\n  function slug(value, base) {\n    if (!isSet(value)) return value;\n    let path = String(value).trim();\n    try {\n      path = new URL(path, base || location.href).pathname;\n    } catch {}\n    const parts = path.split(\"/\").filter(Boolean);\n    if (!parts.length) return String(value).trim();\n    try {\n      return decodeURIComponent(parts[parts.length - 1]);\n    } catch {\n      return parts[parts.length - 1];\n    }\n  }\n\n  /**\n   * One field of an item: `selector`, `selector@attr`, `@attr` or `.` (see the fields slot),\n   * each optionally ending `|slug`: the value's last path segment (an item's id from the\n   * link to its own page, `a@href|slug`).\n   */\n  function field(item, rawSpec, base) {\n    const piped = /\\|\\s*slug\\s*$/.exec(rawSpec);\n    if (piped) return slug(field(item, rawSpec.slice(0, piped.index).trim(), base), base);\n    const spec = rawSpec;\n    if (spec === \".\") return valueOf(item);\n    let selector = spec;\n    let attr = null;\n    const at = spec.lastIndexOf(\"@\");\n    if (at >= 0 && /^[A-Za-z_:][-A-Za-z0-9_:.]*$/.test(spec.slice(at + 1))) {\n      selector = spec.slice(0, at).trim();\n      attr = spec.slice(at + 1);\n    }\n    const el = selector ? item.querySelector(selector) : item;\n    if (!el) return null;\n    if (!attr) return valueOf(el);\n    const raw = el.getAttribute(attr);\n    if (raw === null) return null;\n    return attr === \"href\" || attr === \"src\" || attr === \"action\" ? absolute(raw, base) : raw.trim();\n  }\n\n  /** A number from text: \"$1,234.50\", \"£9.50\", \"1.234,50 €\", \"Qty 2\". Null when none. */\n  function number(value) {\n    if (value === null || value === undefined) return null;\n    if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n    const match = String(value).replace(/\\s/g, \"\").match(/-?\\d[\\d.,']*/);\n    if (!match) return null;\n    let s = match[0].replace(/'/g, \"\").replace(/[.,]$/, \"\");\n    const comma = s.lastIndexOf(\",\");\n    const dot = s.lastIndexOf(\".\");\n    if (comma > dot) {\n      const decimals = s.length - comma - 1;\n      s = dot === -1 && decimals === 3 ? s.replace(/,/g, \"\") : s.replace(/\\./g, \"\").replace(\",\", \".\");\n    } else {\n      s = s.replace(/,/g, \"\");\n    }\n    const n = Number(s);\n    return Number.isFinite(n) ? n : null;\n  }\n\n  /** Every number in a text (for \"the page shows this price\"). */\n  function numbers(value) {\n    return (String(value || \"\").match(/-?\\d[\\d.,']*\\d|\\d/g) || []).map(number).filter((n) => n !== null);\n  }\n\n  /** A time of day as HH:MM from \"9:00 AM\", \"2:30 pm\", \"14:30\". Null when it is not one. */\n  function clock(value) {\n    const m = /(\\d{1,2})[:.h](\\d{2})\\s*([ap])?\\.?\\s*m?\\.?/i.exec(String(value || \"\"));\n    if (!m) return null;\n    let hour = Number(m[1]);\n    const minute = Number(m[2]);\n    const half = m[3] ? m[3].toLowerCase() : \"\";\n    if (half === \"p\" && hour < 12) hour += 12;\n    if (half === \"a\" && hour === 12) hour = 0;\n    if (hour > 23 || minute > 59) return null;\n    return `${String(hour).padStart(2, \"0\")}:${String(minute).padStart(2, \"0\")}`;\n  }\n\n  function coerce(name, raw) {\n    if (name === \"price\" || name === \"subtotal\" || name === \"total\") return number(raw);\n    if (name === \"quantity\") {\n      const n = number(raw);\n      return n === null ? null : Math.round(n);\n    }\n    return raw;\n  }\n\n  /** Read the fields slot `fieldsSlot` from one element. Required fields that read nothing throw. */\n  function readFields(root, fieldsSlot, base, required) {\n    const specs = slot(fieldsSlot);\n    const out = {};\n    for (const [name, spec] of Object.entries(specs)) {\n      const raw = field(root, spec, base);\n      if ((raw === null || raw === \"\") && required && required.includes(name)) {\n        throw new Error(`slot \"${fieldsSlot}\" field \"${name}\" (${spec}) read nothing on ${where(root)}`);\n      }\n      out[name] = coerce(name, raw);\n      if ((name === \"price\" || name === \"subtotal\" || name === \"total\") && isSet(raw)) {\n        out[`${name}_text`] = String(raw).trim();\n      }\n    }\n    return out;\n  }\n\n  /** Read every item a selector slot matches, each through the fields slot. */\n  function readItems(root, itemSlot, fieldsSlot, input, base) {\n    return qa(itemSlot, input, root).map((item) => readFields(item, fieldsSlot, base));\n  }\n\n  /** Is this value an item's URL or site path rather than a bare id? */\n  function urlLike(value) {\n    return typeof value === \"string\" && /^(https?:\\/\\/|\\/)/i.test(value.trim());\n  }\n\n  /**\n   * The path placeholders' values a URL or path carries for this URL slot's path, or null\n   * when its path is not one the slot makes. Matched at the end of the path, so\n   * `/collections/all/products/mug` gives `{ id: \"mug\" }` for `/products/{id}`.\n   */\n  function pathValues(pathPart, value) {\n    let path;\n    try {\n      path = new URL(String(value).trim(), location.href).pathname;\n    } catch {\n      return null;\n    }\n    const keys = [];\n    const source = pathPart\n      .replace(/\\/+$/, \"\")\n      .split(PLACEHOLDER)\n      .map((part, i) => {\n        if (i % 2) {\n          keys.push(part);\n          return \"([^/]+)\";\n        }\n        return part.replace(/[.*+?^$()|[\\]{}\\\\]/g, \"\\\\$&\");\n      })\n      .join(\"\");\n    if (!keys.length) return null;\n    const m = new RegExp(`${source}/?$`).exec(path);\n    if (!m) return null;\n    const out = {};\n    keys.forEach((key, i) => {\n      try {\n        out[key] = decodeURIComponent(m[i + 1]);\n      } catch {\n        out[key] = m[i + 1];\n      }\n    });\n    return out;\n  }\n\n  /**\n   * A URL slot filled from `values` (then `defaults`), with the values it used: path\n   * placeholders must be given, as a bare value or as the item's own URL or path (whose\n   * path the slot's path matches); a query pair whose placeholder has no value is left out.\n   */\n  function resolveUrl(template, values, defaults) {\n    const raw = String(template);\n    const cut = raw.indexOf(\"?\");\n    const pathPart = cut < 0 ? raw : raw.slice(0, cut);\n    const queryPart = cut < 0 ? \"\" : raw.slice(cut + 1);\n    const given = { ...(values || {}) };\n    for (const [key, v] of Object.entries(given)) {\n      if (!urlLike(v) || !pathPart.includes(`{${key}}`)) continue;\n      const found = pathValues(pathPart, v);\n      if (!found) {\n        throw new Error(`\"${key}\" is ${v}, which is not a page ${pathPart} names: pass its id, or the URL of its own page`);\n      }\n      Object.assign(given, found);\n    }\n    const used = {};\n    const pick = (key) => {\n      const v = isSet(given[key]) ? given[key] : isSet(defaults && defaults[key]) ? defaults[key] : null;\n      if (v !== null) used[key] = String(v);\n      return v;\n    };\n    const path = pathPart.replace(PLACEHOLDER, (_, key) => {\n      const v = pick(key);\n      if (v === null) throw new Error(`the URL ${template} needs \"${key}\", which the call did not give`);\n      return encodeURIComponent(String(v));\n    });\n    const url = new URL(path, location.href);\n    for (const pair of queryPart.split(\"&\").filter(Boolean)) {\n      const eq = pair.indexOf(\"=\");\n      const key = decodeURIComponent(eq < 0 ? pair : pair.slice(0, eq));\n      let missing = false;\n      const value = (eq < 0 ? \"\" : pair.slice(eq + 1)).replace(PLACEHOLDER, (_, k) => {\n        const v = pick(k);\n        if (v === null) missing = true;\n        return v === null ? \"\" : String(v);\n      });\n      if (!missing) url.searchParams.append(key, value);\n    }\n    return { url: url.href, values: used };\n  }\n\n  /** A URL slot filled (see {@link resolveUrl}): the URL alone. */\n  function fillUrl(template, values, defaults) {\n    return resolveUrl(template, values, defaults).url;\n  }\n\n  /** Fetch a same-origin page as a document (the shopper's cookies go with it). */\n  async function fetchDoc(url) {\n    const res = await fetch(url, { credentials: \"same-origin\", headers: { accept: \"text/html\" } });\n    if (!res.ok) throw new Error(`${where({ __rtUrl: url })} answered HTTP ${res.status}`);\n    const doc = new DOMParser().parseFromString(await res.text(), \"text/html\");\n    doc.__rtUrl = res.url || url;\n    return doc;\n  }\n\n  /** Poll `check` until it answers truthy; throws `what` after `timeoutMs`. */\n  async function waitFor(check, what, timeoutMs) {\n    const limit = timeoutMs || 10000;\n    const started = Date.now();\n    for (;;) {\n      let value;\n      try {\n        value = await check();\n      } catch {\n        value = undefined;\n      }\n      if (value) return value;\n      if (Date.now() - started > limit) throw new Error(`${what} (waited ${Math.round(limit / 1000)} s on ${where()})`);\n      await sleep(50);\n    }\n  }\n\n  /** Resolve once the page has had no DOM change for `ms` (at most `maxMs`). */\n  function quiet(ms, maxMs) {\n    const calm = ms || 250;\n    return new Promise((resolve) => {\n      let timer;\n      let cap;\n      const observer = new MutationObserver(() => {\n        clearTimeout(timer);\n        timer = setTimeout(done, calm);\n      });\n      function done() {\n        observer.disconnect();\n        clearTimeout(timer);\n        clearTimeout(cap);\n        resolve();\n      }\n      observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });\n      timer = setTimeout(done, calm);\n      cap = setTimeout(done, maxMs || 5000);\n    });\n  }\n\n  /** The real click sequence a person's mouse makes: over, down, focus, up, click. */\n  function click(el) {\n    try {\n      el.scrollIntoView({ block: \"center\", inline: \"center\" });\n    } catch {}\n    const rect = el.getBoundingClientRect();\n    const at = { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 };\n    const base = { bubbles: true, cancelable: true, composed: true, button: 0, ...at };\n    const Pointer = typeof PointerEvent === \"function\" ? PointerEvent : MouseEvent;\n    const pointer = { ...base, pointerType: \"mouse\", isPrimary: true };\n    el.dispatchEvent(new Pointer(\"pointerover\", pointer));\n    el.dispatchEvent(new MouseEvent(\"mouseover\", base));\n    el.dispatchEvent(new Pointer(\"pointerdown\", { ...pointer, buttons: 1 }));\n    el.dispatchEvent(new MouseEvent(\"mousedown\", { ...base, buttons: 1 }));\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    el.dispatchEvent(new Pointer(\"pointerup\", pointer));\n    el.dispatchEvent(new MouseEvent(\"mouseup\", base));\n    el.click();\n  }\n\n  /** Is a control switched off (disabled, or aria-disabled)? */\n  function isDisabled(el) {\n    return Boolean(el.disabled) || el.getAttribute(\"aria-disabled\") === \"true\";\n  }\n\n  /**\n   * The control `find` returns (a function, or a selector on this page), once it is there\n   * and enabled: a framework draws a pick's effect after the script's turn (Add stays\n   * disabled until the size just chosen renders). After `timeoutMs` (5 s) it throws that\n   * `subject` matched nothing, or stays disabled, on `root`'s page (else this one).\n   */\n  async function ready(find, subject, timeoutMs, root) {\n    const get = typeof find === \"function\" ? find : () => document.querySelector(find);\n    const limit = timeoutMs || 5000;\n    const started = Date.now();\n    for (;;) {\n      let el = null;\n      try {\n        el = get();\n      } catch {}\n      if (el && el.isConnected && !isDisabled(el)) return el;\n      if (Date.now() - started > limit) {\n        const state = el && el.isConnected ? \"stays disabled\" : \"matched nothing\";\n        throw new Error(`${subject} ${state} on ${where(root)} (waited ${Math.round(limit / 1000)} s)`);\n      }\n      await sleep(50);\n    }\n  }\n\n  /** The element a selector slot names, once it is there and enabled. */\n  function qReady(name, input, root, timeoutMs) {\n    const selector = sel(name, input);\n    return ready(() => (root || document).querySelector(selector), `slot \"${name}\" (${selector})`, timeoutMs, root);\n  }\n\n  /**\n   * Press every element `selector` matches (on `root`, else this page), in page order, each\n   * once it is there and enabled, the page given a moment between presses — e.g. the first\n   * choice of each option group, before an Add button that needs them.\n   */\n  async function pressEach(selector, root, what) {\n    const scope = root || document;\n    const count = scope.querySelectorAll(selector).length;\n    if (!count) throw new Error(`${what}: ${selector} matched nothing on ${where(scope.documentElement || scope)}`);\n    for (let i = 0; i < count; i++) {\n      const el = await ready(() => scope.querySelectorAll(selector)[i], `${what}: match ${i + 1} of ${selector}`, 0, root);\n      click(el);\n      await sleep(150);\n    }\n    return count;\n  }\n\n  /**\n   * A check's seed: press `picks` (every match, see {@link pressEach}; none when null), then\n   * the add control `button` once it is enabled (both selectors, on `root`, else this page).\n   * A page still hydrating ignores the first presses, so picks that leave the button\n   * disabled are pressed again, twice at most. Throws a sentence naming the slots.\n   */\n  async function seed(picks, button, root, what) {\n    const scope = root || document;\n    const label = what || \"the seed\";\n    for (let round = 1; ; round++) {\n      if (picks) await pressEach(picks, scope, `${label}'s picks`);\n      try {\n        const el = await ready(() => scope.querySelector(button), \"\", 4000, root);\n        click(el);\n        return;\n      } catch {}\n      if (round >= 3) {\n        const there = scope.querySelector(button);\n        throw new Error(\n          !there\n            ? `${label}: its add control ${button} is not on ${where(scope.documentElement || scope)}`\n            : picks\n              ? `${label}: its add control ${button} stays disabled after pressing ${picks}`\n              : `${label}: its add control ${button} stays disabled; when adding needs a choice first (a size, a colour), name those controls in seed_picks`,\n        );\n      }\n    }\n  }\n\n  /** Set a control's value the way the page's framework sees a person do it. */\n  function setNative(el, value) {\n    const proto =\n      el.tagName === \"SELECT\"\n        ? HTMLSelectElement.prototype\n        : el.tagName === \"TEXTAREA\"\n          ? HTMLTextAreaElement.prototype\n          : HTMLInputElement.prototype;\n    const descriptor = Object.getOwnPropertyDescriptor(proto, \"value\");\n    if (descriptor && descriptor.set) descriptor.set.call(el, value);\n    else el.value = value;\n  }\n\n  function setValue(el, value) {\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    setNative(el, String(value));\n    el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"insertReplacementText\", data: String(value) }));\n    el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n  }\n\n  /** Type into a text box key by key (keydown, keypress, input, keyup), then change. */\n  async function type(el, value) {\n    if (typeof el.focus === \"function\") el.focus({ preventScroll: true });\n    setNative(el, \"\");\n    el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"deleteContentBackward\" }));\n    for (const ch of String(value)) {\n      const key = { key: ch, bubbles: true, cancelable: true };\n      el.dispatchEvent(new KeyboardEvent(\"keydown\", key));\n      el.dispatchEvent(new KeyboardEvent(\"keypress\", key));\n      setNative(el, el.value + ch);\n      el.dispatchEvent(new InputEvent(\"input\", { bubbles: true, inputType: \"insertText\", data: ch }));\n      el.dispatchEvent(new KeyboardEvent(\"keyup\", key));\n      await sleep(5);\n    }\n    el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n  }\n\n  /** Press Enter in a box; like a browser, submit its form unless the page handled the key. */\n  function pressEnter(el) {\n    const init = { key: \"Enter\", code: \"Enter\", keyCode: 13, which: 13, bubbles: true, cancelable: true };\n    const unhandled = el.dispatchEvent(new KeyboardEvent(\"keydown\", init));\n    el.dispatchEvent(new KeyboardEvent(\"keypress\", init));\n    if (unhandled && el.form) {\n      if (typeof el.form.requestSubmit === \"function\") el.form.requestSubmit();\n      else el.form.submit();\n    }\n    el.dispatchEvent(new KeyboardEvent(\"keyup\", init));\n  }\n\n  /**\n   * The label a person reads for a control: its <label>, aria-label or aria-labelledby, a\n   * fieldset's legend, a wrapping label, its name — or, for a group drawn without any (a\n   * row of size buttons), the short text just before it (\"Select Size\" → \"Size\").\n   */\n  function labelOf(el) {\n    const doc = el.ownerDocument;\n    if (el.id && doc) {\n      const label = doc.querySelector(`label[for=\"${cssString(el.id)}\"]`);\n      if (label) return text(label);\n    }\n    const aria = el.getAttribute(\"aria-label\");\n    if (aria) return aria.trim();\n    const by = el.getAttribute(\"aria-labelledby\");\n    if (by && doc) {\n      const named = by\n        .split(/\\s+/)\n        .map((id) => text(doc.getElementById(id)))\n        .filter(Boolean)\n        .join(\" \");\n      if (named) return named;\n    }\n    const legend = el.tagName === \"FIELDSET\" ? el.querySelector(\"legend\") : null;\n    if (legend) return text(legend);\n    const wrap = el.closest(\"label\");\n    if (wrap && wrap !== el) return text(wrap);\n    if (el.getAttribute(\"name\")) return el.getAttribute(\"name\");\n    const before = el.previousElementSibling;\n    if (before && !before.querySelector(\"button, input, select, textarea, a\")) {\n      const said = text(before)\n        .replace(/^(select|choose|pick)\\s+(a\\s+|an\\s+|your\\s+)?/i, \"\")\n        .replace(/\\s*[:*]\\s*$/, \"\");\n      // A label is a few words (\"Size\"), not a price or a count beside the group.\n      if (said && said.length <= 40 && /[a-z]/i.test(said) && !/\\d/.test(said)) return said;\n    }\n    return \"\";\n  }\n\n  /** The choices of an option control: a select, a radio group, or a group of buttons. */\n  function choices(control) {\n    if (control.tagName === \"SELECT\") {\n      return [...control.options].map((o) => ({ label: text(o), value: o.value }));\n    }\n    const radios = [...control.querySelectorAll(\"input[type=radio], input[type=checkbox]\")];\n    if (radios.length) return radios.map((r) => ({ label: labelOf(r) || r.value, value: r.value, el: r }));\n    return [...control.querySelectorAll(\"button, [role=radio], [role=option]\")].map((b) => ({\n      label: text(b),\n      value: b.getAttribute(\"data-value\") || b.value || text(b),\n      el: b,\n    }));\n  }\n\n  /** An option control read as { name, values: [{ label, value }] }. */\n  function readOption(control) {\n    return { name: labelOf(control), values: choices(control).map(({ label, value }) => ({ label, value })) };\n  }\n\n  /** Pick `wanted` (a label or a value, any case) on an option control, as a person would. */\n  function choose(control, wanted, what) {\n    const want = norm(wanted);\n    const options = choices(control);\n    const hit = options.find((o) => norm(o.value) === want || norm(o.label) === want);\n    if (!hit) {\n      throw new Error(`${what}: no choice \"${wanted}\" (choices: ${options.map((o) => o.label).join(\", \")})`);\n    }\n    if (control.tagName === \"SELECT\") setValue(control, hit.value);\n    else click(hit.el);\n    return hit.label;\n  }\n\n  /** Where a link or a GET form's submit control goes; null for a POST form or no target. */\n  function controlTarget(el, base) {\n    const link = el.closest(\"a[href]\");\n    if (link) return absolute(link.getAttribute(\"href\"), base);\n    const form = el.form || el.closest(\"form\");\n    if (!form) return null;\n    const method = (el.getAttribute(\"formmethod\") || form.getAttribute(\"method\") || \"get\").toLowerCase();\n    if (method !== \"get\") return null;\n    const url = new URL(el.getAttribute(\"formaction\") || form.getAttribute(\"action\") || base, base);\n    url.search = \"\";\n    for (const control of form.elements) {\n      if (!control.name || control.disabled) continue;\n      const type = (control.type || \"\").toLowerCase();\n      if ([\"submit\", \"button\", \"image\", \"reset\", \"file\"].includes(type) && control !== el) continue;\n      if ((type === \"checkbox\" || type === \"radio\") && !control.checked) continue;\n      url.searchParams.append(control.name, control.value || \"\");\n    }\n    return url.href;\n  }\n\n  /** Go to `url` once the tool has returned (the Snippet defers a location change). */\n  function navigate(url) {\n    location.assign(url);\n  }\n\n  /** The live page's visible text, normalized. */\n  function pageText() {\n    return norm(document.body ? document.body.innerText : \"\");\n  }\n\n  /**\n   * A same-origin page's text as the site serves it now, normalized (fetched fresh; its\n   * scripts, styles and templates left out, so only what a person could read counts).\n   */\n  async function servedText(url) {\n    const doc = await fetchDoc(url);\n    if (!doc.body) return \"\";\n    doc.body.querySelectorAll(\"script, style, noscript, template\").forEach((el) => el.remove());\n    return norm(doc.body.textContent);\n  }\n\n  /** Does `path` match an SDK page pattern (`*` = any run of characters)? */\n  function matchPath(pattern, path) {\n    const escape = (part) => part.replace(/[.+?^$()|[\\]{}\\\\]/g, \"\\\\$&\");\n    const source = String(pattern).split(\"*\").map(escape).join(\".*\");\n    return new RegExp(\"^\" + source + \"$\").test(path);\n  }\n\n  /** A form field a person has typed into (hidden fields and buttons don't count). */\n  function isTyped(field) {\n    const type = (field.type || \"text\").toLowerCase();\n    if ([\"hidden\", \"submit\", \"button\", \"image\", \"reset\", \"checkbox\", \"radio\"].includes(type)) return false;\n    if (field.tagName === \"SELECT\") return false;\n    return isSet(field.value);\n  }\n\n  // ── An item by the name a visitor uses (NEK-1102) ──\n\n  /** Text as names compare: accents, case, apostrophes, punctuation and spacing aside. */\n  function fold(value) {\n    return String(value == null ? \"\" : value)\n      .normalize(\"NFD\")\n      .replace(/\\p{M}+/gu, \"\")\n      .toLowerCase()\n      .replace(/['’‘`]/g, \"\")\n      .replace(/[^\\p{L}\\p{N}]+/gu, \" \")\n      .trim();\n  }\n\n  /** An element's text with a space between its pieces: \"2021\" then \"Harbour Blend\" is two words. */\n  function spaced(el) {\n    if (!el) return \"\";\n    const parts = [];\n    const walk = (node) => {\n      for (const child of node.childNodes) {\n        if (child.nodeType === 3) parts.push(child.nodeValue);\n        else if (child.nodeType === 1 && !/^(script|style|noscript|template|svg)$/i.test(child.tagName)) walk(child);\n      }\n    };\n    walk(el);\n    return parts.join(\" \").replace(/\\s+/g, \" \").trim();\n  }\n\n  /** A URL's or path's path, without its query, hash or trailing slash (null when not one). */\n  function pathOf(url, base) {\n    try {\n      return new URL(String(url), base || location.href).pathname.replace(/\\/+$/, \"\") || \"/\";\n    } catch {\n      return null;\n    }\n  }\n\n  /**\n   * Does `path` match a page pattern? `*` or a `{name}` placeholder is one path segment, `**`\n   * any depth: `/shop/*` is an item's page, never `/shop/a/b`.\n   */\n  function isPage(pattern, path) {\n    const source = String(pattern)\n      .replace(/^https?:\\/\\/[^/]+/i, \"\")\n      .split(/[?#]/)[0]\n      .replace(/\\/+$/, \"\")\n      .split(/(\\*\\*|\\*|\\{[A-Za-z_][A-Za-z0-9_]*\\})/)\n      .map((part, i) => (i % 2 ? (part === \"**\" ? \".*\" : \"[^/]+\") : part.replace(/[.+?^$()|[\\]{}\\\\]/g, \"\\\\$&\")))\n      .join(\"\");\n    return new RegExp(`^${source || \"/\"}$`).test(String(path).replace(/\\/+$/, \"\") || \"/\");\n  }\n\n  const HEADING = \"h1, h2, h3, h4, h5, h6, [role=heading]\";\n\n  /**\n   * The items a page links to: one entry per same-origin path matching `link`, with every name\n   * the page gives it (a heading in the link, else the heading of the card the link sits in,\n   * its label or title, its text, an image's alt) and its path's last segment (`id`).\n   */\n  function itemLinks(root, link, base) {\n    const at = base || (root && root.__rtUrl) || location.href;\n    const origin = new URL(at, location.href).origin;\n    const byPath = new Map();\n    const anchors = [...root.querySelectorAll(\"a[href]\")];\n    const pathOfLink = (a) => {\n      try {\n        const url = new URL(a.getAttribute(\"href\"), at);\n        return url.origin === origin ? url.pathname.replace(/\\/+$/, \"\") || \"/\" : null;\n      } catch {\n        return null;\n      }\n    };\n    for (const a of anchors) {\n      const path = pathOfLink(a);\n      if (!path || !isPage(link, path)) continue;\n      let entry = byPath.get(path);\n      if (!entry) {\n        entry = { id: slug(path), path, url: origin + path, name: \"\", names: [] };\n        byPath.set(path, entry);\n      }\n      const add = (value) => {\n        const t = String(value || \"\").replace(/\\s+/g, \" \").trim();\n        if (t && t.length <= 300 && /[\\p{L}\\p{N}]/u.test(t) && !entry.names.includes(t)) entry.names.push(t);\n      };\n      const heads = [...a.querySelectorAll(HEADING)];\n      for (const h of heads) add(spaced(h));\n      if (!heads.length) {\n        // A link whose text is not the name (\"Read more\", a picture): its card's heading, when\n        // the card links to no other item.\n        let card = a.parentElement;\n        for (let up = 0; card && up < 4; up += 1, card = card.parentElement) {\n          const other = [...card.querySelectorAll(\"a[href]\")].some((b) => {\n            const p = pathOfLink(b);\n            return p && p !== path && isPage(link, p);\n          });\n          if (other) break;\n          const h = card.querySelector(HEADING);\n          if (h) {\n            add(spaced(h));\n            break;\n          }\n        }\n      }\n      add(a.getAttribute(\"aria-label\"));\n      add(a.getAttribute(\"title\"));\n      add(spaced(a));\n      for (const img of a.querySelectorAll(\"img[alt]\")) add(img.getAttribute(\"alt\"));\n    }\n    for (const entry of byPath.values()) entry.name = entry.names[0] || entry.id;\n    return [...byPath.values()];\n  }\n\n  /** Does one of an entry's names (or its id, in words) hold every word of `words`? */\n  function holds(entry, words) {\n    return [...entry.names, entry.id].some((n) => {\n      const have = new Set(fold(n).split(\" \"));\n      return words.every((w) => have.has(w));\n    });\n  }\n\n  /** How close an entry's names come to `words`: whole words shared, then words begun alike. */\n  function closeness(entry, words) {\n    let best = 0;\n    for (const n of [...entry.names, entry.id]) {\n      const have = fold(n).split(\" \").filter(Boolean);\n      let score = 0;\n      for (const w of words) {\n        if (have.includes(w)) score += 1;\n        else if (w.length >= 3 && have.some((h) => h.length >= 3 && (h.startsWith(w) || w.startsWith(h)))) score += 0.5;\n      }\n      best = Math.max(best, score);\n    }\n    return best;\n  }\n\n  /**\n   * The one entry (as `itemLinks` gives them) a visitor's name picks: the one one of whose\n   * names is the name (case, accents and punctuation aside), else the one whose name holds\n   * every word of it (\"Harbour Blend\" finds \"2021 Harbour Blend Coffee\"), never the closest\n   * guess. More than one, or none, throws a plain error naming the closest with their ids.\n   */\n  function matchItem(name, entries, what) {\n    const noun = what || \"item\";\n    const list = entries || [];\n    const wanted = fold(name);\n    const words = wanted.split(\" \").filter(Boolean);\n    if (!words.length) throw new Error(`name the ${noun}: its name as the site shows it, its id, or its page's URL`);\n    const named = (e) => `\"${e.name}\"${e.parent ? ` in \"${e.parent.name}\"` : \"\"} (id ${e.id})`;\n    const exact = list.filter((e) => e.names.some((n) => fold(n) === wanted) || fold(e.id) === wanted);\n    if (exact.length === 1) return exact[0];\n    const holding = exact.length ? exact : list.filter((e) => holds(e, words));\n    if (holding.length === 1) return holding[0];\n    if (holding.length > 1) {\n      const more = holding.length > 6 ? \", …\" : \"\";\n      throw new Error(\n        `\"${name}\" names ${holding.length} ${noun}s here: ${holding.slice(0, 6).map(named).join(\", \")}${more}. Pass one's full name or id.`,\n      );\n    }\n    if (!list.length) throw new Error(`no ${noun} is named \"${name}\": the site lists no ${noun}s where it was looked for`);\n    const closest = list\n      .map((e) => ({ e, score: closeness(e, words) }))\n      .filter((x) => x.score > 0)\n      .sort((a, b) => b.score - a.score)\n      .slice(0, 3)\n      .map((x) => x.e);\n    const shown = closest.length\n      ? `The closest: ${closest.map(named).join(\", \")}.`\n      : `It lists ${list.slice(0, 3).map(named).join(\", \")}${list.length > 3 ? ` and ${list.length - 3} more` : \"\"}.`;\n    throw new Error(`No ${noun} is named \"${name}\" on this site. ${shown}`);\n  }\n\n  /**\n   * A same-origin page as the browser draws it: loaded in a hidden frame, `read(doc)` once\n   * `ready(doc)` holds (or, when `ms` — 15 s by default — runs out, the page as it is by\n   * then), the frame removed after. Throws when the page does not open in a frame at all (a\n   * site that refuses to be framed).\n   */\n  async function inFrame(url, ready, read, ms) {\n    const frame = document.createElement(\"iframe\");\n    frame.setAttribute(\"aria-hidden\", \"true\");\n    frame.tabIndex = -1;\n    frame.style.cssText =\n      \"position:fixed;left:-12000px;top:0;width:1280px;height:900px;border:0;visibility:hidden;pointer-events:none\";\n    frame.src = url;\n    (document.body || document.documentElement).append(frame);\n    const limit = ms || 15000;\n    const started = Date.now();\n    try {\n      for (;;) {\n        let doc = null;\n        try {\n          doc = frame.contentDocument;\n        } catch {}\n        const loaded = Boolean(doc && doc.body && doc.readyState !== \"loading\" && doc.location.href !== \"about:blank\");\n        let done = false;\n        if (loaded) {\n          doc.__rtUrl = doc.location.href;\n          try {\n            done = !ready || Boolean(ready(doc));\n          } catch {}\n        }\n        if (done || (loaded && Date.now() - started > limit)) return await read(doc);\n        if (Date.now() - started > limit) {\n          throw new Error(`${where({ __rtUrl: url })} did not open in a hidden frame within ${Math.round(limit / 1000)} s (the site may refuse to be framed)`);\n        }\n        await sleep(100);\n      }\n    } finally {\n      frame.remove();\n    }\n  }\n\n  /**\n   * The item a caller names, found the way a visitor finds it (NEK-1102). `name` is its name\n   * or title as the site shows it, or the shorter one a person uses (\"Harbour Blend\" for\n   * \"2021 Harbour Blend Coffee\"), its id, or its page's URL or path. `where`:\n   * - `link` (required): the item pages' pattern, `*` one path segment, `**` any depth\n   *   (`/products/*`);\n   * - `list`: the page or pages that link the items — a listing, or a search whose URL takes\n   *   the name as `{query}` (`/search?q={query}`); `/` by default;\n   * - `page`: the item page's URL with `{id}` (`/products/{id}`): an id the listing does not\n   *   show opens there, when the site has that page;\n   * - `via`: the pattern of the pages that list the items themselves when `list` links only\n   *   to those (a course's page listing its lessons): read when `list` names none;\n   * - `what`: the item's noun, for the errors (`\"product\"`, `\"lesson\"`);\n   * - `ms`: how long it may look (30 s by default; `max_pages` via-pages at most, 12).\n   * A URL or path opens directly. Each page is read as the server sends it, or — when script\n   * draws its links — as the browser draws it (`inFrame`). Returns `{ id, name, path, url }`,\n   * with `parent` (`{ id, name, path, url }`) for an item found via one. A name that answers\n   * to no item or several throws a plain error naming the closest items with their ids\n   * (`matchItem`).\n   */\n  async function findItem(name, where_) {\n    const opts = where_ || {};\n    if (!isSet(opts.link)) throw new Error(\"findItem needs `link`: the item pages' pattern, e.g. /products/*\");\n    const noun = opts.what || \"item\";\n    const raw = String(name == null ? \"\" : name).trim();\n    if (!raw) throw new Error(`name the ${noun}: its name as the site shows it, its id, or its page's URL`);\n    const deadline = Date.now() + (opts.ms || 30000);\n    const left = () => deadline - Date.now();\n    const found = (e) => ({\n      id: e.id,\n      name: e.name || null,\n      path: e.path,\n      url: e.url,\n      ...(e.parent ? { parent: { id: e.parent.id, name: e.parent.name, path: e.parent.path, url: e.parent.url } } : {}),\n    });\n    // Its own page's URL or path.\n    if (urlLike(raw)) {\n      let url = null;\n      try {\n        url = new URL(raw, location.href);\n      } catch {}\n      const path = url && url.origin === location.origin ? pathOf(url.href) : null;\n      if (path && (isPage(opts.link, path) || (opts.page && isPage(opts.page, path)))) {\n        return { id: slug(path), name: null, path, url: location.origin + path };\n      }\n      throw new Error(`${raw} is not a ${noun}'s page on this site (${opts.link}): pass its name, its id, or its page's URL`);\n    }\n    // Its name or id, where the site lists it.\n    const entries = new Map();\n    const parents = new Map();\n    const take = (doc, base, parent) => {\n      for (const e of itemLinks(doc, opts.link, base)) {\n        const had = entries.get(e.path);\n        if (had) {\n          for (const n of e.names) if (!had.names.includes(n)) had.names.push(n);\n        } else entries.set(e.path, parent ? { ...e, parent } : e);\n      }\n      if (opts.via && !parent) {\n        for (const e of itemLinks(doc, opts.via, base)) if (!parents.has(e.path) && !entries.has(e.path)) parents.set(e.path, e);\n      }\n    };\n    const has = (doc, withVia) =>\n      itemLinks(doc, opts.link, doc.__rtUrl).length > 0 || (withVia && itemLinks(doc, opts.via, doc.__rtUrl).length > 0);\n    // A page's links as the server sends them, else as the browser draws them.\n    const read = async (url, parent, ms) => {\n      let doc = null;\n      try {\n        doc = await fetchDoc(url);\n      } catch {}\n      if (doc && has(doc, !parent && opts.via)) return take(doc, doc.__rtUrl, parent);\n      if (left() < 500) return doc ? take(doc, doc.__rtUrl, parent) : undefined;\n      try {\n        await inFrame(url, (d) => has(d, !parent && opts.via), (d) => take(d, d.__rtUrl, parent), Math.min(ms, left()));\n      } catch {\n        if (doc) take(doc, doc.__rtUrl, parent);\n      }\n    };\n    for (const list of [].concat(opts.list || \"/\")) {\n      const url = new URL(String(list).replace(/\\{query\\}/g, encodeURIComponent(raw)), location.href).href;\n      await read(url, null, 15000);\n    }\n    const words = fold(raw).split(\" \").filter(Boolean);\n    const any = () => [...entries.values()].some((e) => fold(e.id) === fold(raw) || holds(e, words));\n    if (opts.via && parents.size && !any()) {\n      // Parts inside items: read every item page that lists them, a few at a time (a part's\n      // name may repeat in another item: the error then names both).\n      const queue = [...parents.values()].slice(0, opts.max_pages || 12);\n      const worker = async () => {\n        while (queue.length && left() > 500) {\n          const parent = queue.shift();\n          await read(parent.url, parent, 10000);\n        }\n      };\n      await Promise.all([worker(), worker(), worker()]);\n    }\n    // An id no listing shows (a later page of it, an item it leaves out) opens on its own page\n    // when the site has one.\n    if (!any() && opts.page && !/\\s/.test(raw)) {\n      const url = new URL(String(opts.page).replace(PLACEHOLDER, () => encodeURIComponent(raw)), location.href);\n      try {\n        const res = await fetch(url.href, { credentials: \"same-origin\", headers: { accept: \"text/html\" } });\n        if (res.ok) {\n          const path = pathOf(url.href);\n          return { id: raw, name: null, path, url: location.origin + path };\n        }\n      } catch {}\n    }\n    return found(matchItem(raw, [...entries.values()], noun));\n  }\n\n  return {\n    sleep, norm, where, slot, fill, sel, q, qMaybe, qa, text, valueOf, field, slug, number,\n    numbers, clock, readFields, readItems, urlLike, resolveUrl, fillUrl, fetchDoc, waitFor,\n    quiet, click, isDisabled, ready, qReady, pressEach, seed, setValue, type, pressEnter, labelOf,\n    readOption, choose, controlTarget, navigate, pageText, servedText, matchPath, isTyped,\n    fold, isPage, itemLinks, matchItem, inFrame, findItem,\n  };\n})();\nconst isOpen = (drawer) => {\n  if (!drawer) return false;\n  const rect = drawer.getBoundingClientRect();\n  return rect.left < window.innerWidth && rect.right > 0 && getComputedStyle(drawer).visibility !== \"hidden\";\n};\n\n// The shopper's cart drawer is the site's own route to its checkout link.\nlet drawer = document.querySelector(\"#cartDrawer\");\nif (!isOpen(drawer)) {\n  const cartButton = document.querySelector('#cartBtn, button[aria-label=\"Sepetim\"]');\n  if (!cartButton) throw new Error(\"I could not find the site's Sepetim button to open the cart.\");\n  rt.click(cartButton);\n  await rt.waitFor(() => {\n    const d = document.querySelector(\"#cartDrawer\");\n    return d && isOpen(d);\n  }, \"the cart drawer to open\", 8000);\n  drawer = document.querySelector(\"#cartDrawer\");\n}\n\nawait rt.waitFor(() => drawer.querySelector(\"#cartBody\"), \"the cart contents to appear\", 5000);\nconst rowEls = [...drawer.querySelectorAll(\"#cartBody h4\")];\nif (!rowEls.length) throw new Error(\"Your cart is empty; add an item before starting checkout.\");\nconst lines = rowEls.map((heading) => {\n  const info = heading.parentElement;\n  const row = info?.parentElement;\n  const price = [...(info?.children || [])].find((el) => el !== heading && !el.querySelector(\"button\"));\n  const quantity = info?.querySelector(\"span\")?.textContent?.trim();\n  return {\n    name: rt.text(heading),\n    quantity: Number(quantity) || 1,\n    unit_price: price ? rt.text(price) : undefined,\n  };\n});\nconst totalEl = drawer.querySelector(\"#cartTotal\");\nconst total = totalEl ? rt.text(totalEl) : \"\";\nif (!total) throw new Error(\"The cart does not show a total, so checkout cannot be started reliably.\");\n\nconst checkoutLink = [...drawer.querySelectorAll('a[href]')].find((a) =>\n  /\\/odeme(?:[/?#]|$)/i.test(a.getAttribute(\"href\") || \"\") && /Ödeme/i.test(rt.text(a)),\n);\nif (!checkoutLink) throw new Error(\"The cart has no Ödeme Sayfası checkout link.\");\nconst target = rt.controlTarget(checkoutLink, location.href);\nif (!target || new URL(target, location.href).origin !== location.origin) {\n  throw new Error(\"The cart's checkout link did not lead to a page on this site.\");\n}\n\n// Read the headings from the checkout page the cart link leads to before handing off.\nconst checkoutDoc = await rt.fetchDoc(target);\nconst pageHeading = checkoutDoc.querySelector(\"h1\");\nconst stepHeading = [...checkoutDoc.querySelectorAll(\"h2\")].find((h) => /Teslimat Bilgileri/i.test(rt.text(h)));\nif (!pageHeading || !stepHeading) {\n  throw new Error(\"The cart's checkout page does not show its first delivery-details step.\");\n}\n\nrt.navigate(target);\nreturn {\n  checkout_path: new URL(target, location.href).pathname,\n  heading: rt.text(pageHeading),\n  step_heading: rt.text(stepHeading),\n  cart: { lines, total },\n  status: \"Checkout is opening with the cart intact. The shopper enters their own details; nothing was filled or submitted.\",\n};\n","mode":"imperative"},"annotations":{"readOnlyHint":false}}]}