@luma-ai/react 0.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +18 -12
  3. package/dist/chunks/src-CI0MDOrd.js +7643 -0
  4. package/dist/chunks/src-CI0MDOrd.js.map +1 -0
  5. package/dist/chunks/support-cursor-pCpYa13-.js +131 -0
  6. package/dist/chunks/support-cursor-pCpYa13-.js.map +1 -0
  7. package/dist/chunks/visitor-call-CDpkyeoR.js +1129 -0
  8. package/dist/chunks/visitor-call-CDpkyeoR.js.map +1 -0
  9. package/dist/chunks/visitor-cobrowse-BIyfnFu3.js +1352 -0
  10. package/dist/chunks/visitor-cobrowse-BIyfnFu3.js.map +1 -0
  11. package/dist/index.js +1 -2
  12. package/dist/next.js +2 -3
  13. package/dist/next.js.map +1 -1
  14. package/dist/react-router.js +2 -3
  15. package/dist/react-router.js.map +1 -1
  16. package/dist/server.js +8 -11
  17. package/dist/server.js.map +1 -1
  18. package/dist/tanstack.js +2 -3
  19. package/dist/tanstack.js.map +1 -1
  20. package/docs/ai-agents.md +5 -5
  21. package/docs/appearance.md +92 -0
  22. package/docs/data-sources.md +18 -18
  23. package/docs/features.md +62 -0
  24. package/docs/hooks.md +22 -8
  25. package/docs/index.md +17 -7
  26. package/docs/options.md +58 -51
  27. package/docs/privacy.md +29 -6
  28. package/docs/server.md +11 -7
  29. package/docs/troubleshooting.md +14 -6
  30. package/package.json +27 -20
  31. package/skills/luma-ai-react/SKILL.md +32 -13
  32. package/dist/chunks/src-dnp1waFV.js +0 -3100
  33. package/dist/chunks/src-dnp1waFV.js.map +0 -1
  34. package/dist/config-CCT7m9eE.d.ts +0 -102
  35. package/dist/index-BdkoFDyP.d.ts +0 -189
  36. package/dist/index.d.ts +0 -3
  37. package/dist/next.d.ts +0 -7
  38. package/dist/react-router.d.ts +0 -10
  39. package/dist/server.d.ts +0 -33
  40. package/dist/tanstack.d.ts +0 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visitor-cobrowse-BIyfnFu3.js","names":["SVG_NS"],"sources":["../../src/cobrowse/mask.ts","../../src/cobrowse/recorder.ts","../../src/cobrowse/visitor-cobrowse.ts"],"sourcesContent":["import type { CobrowsePlaceholder } from \"@luma/assistant-contract/cobrowse-basics\";\nimport { COBROWSE_LIMITS } from \"@luma/assistant-contract/cobrowse-basics\";\nimport { isSensitiveField } from \"../core/page-outline\";\n\n/**\n * What co-browsing (phase 14) may copy of an element, decided in the\n * visitor's browser before anything is sent. The rules, in short:\n * - only what the page draws: no text or attributes of an element that is\n * not rendered (`display: none`, `hidden`, `visibility: hidden`…), see\n * `rendering`;\n * - only the attributes drawing needs (an allowlist): no `data-*` but a few\n * UI state keywords, no labels nobody sees, no tokens in attributes;\n * - nothing the visitor enters: no `value`, `checked` or `selected`; text\n * areas, selects and editable regions are copied empty; the widget never\n * reads a field's value or listens to typing;\n * - password, payment and one-time-code fields (by their attributes and by\n * their resolved label) are empty boxes without even their placeholder;\n * - private regions (`data-luma-private`, the site's own) are empty boxes;\n * - no scripts, inline event handlers, `javascript:` or other non-web URLs;\n * - no iframe content, canvas, video or audio (boxes of their size);\n * - links lose their query and fragment (they can carry tokens).\n */\n\n/** Removed with their whole subtree. */\nconst DROPPED = new Set([\n \"script\",\n \"noscript\",\n \"template\",\n \"meta\",\n \"base\",\n \"datalist\",\n \"slot-fallback\",\n // SVG animation elements can set any attribute, an href included.\n \"animate\",\n \"animatemotion\",\n \"animatetransform\",\n \"set\",\n \"discard\",\n]);\nconst MEDIA = new Set([\n \"video\",\n \"audio\",\n \"canvas\",\n \"object\",\n \"embed\",\n \"applet\",\n]);\nconst FRAMES = new Set([\n \"iframe\",\n \"frame\",\n \"frameset\",\n \"portal\",\n \"fencedframe\",\n]);\nconst FIELDS = new Set([\"input\", \"textarea\", \"select\"]);\n/** Inputs that are buttons (their type is not something typed into). */\nconst BUTTON_INPUTS = new Set([\"submit\", \"button\", \"reset\", \"image\"]);\n/** Attributes holding an address: made absolute, kept only for the web. */\nconst URL_ATTRIBUTES = new Set([\"href\", \"src\", \"xlink:href\", \"background\"]);\n\n/*\n * The attributes the copy keeps: an allowlist of what drawing the page needs\n * (the site's CSS selects on it, or it sizes, places or shows something).\n * Everything else stays on the visitor's page, whatever its value looks\n * like: `data-*` (application data, session tokens, ids), `aria-*` labels\n * and descriptions (text nobody sees on the screen), `title`, `name`,\n * `for`, `form`, `action`, `value` (but where it is drawn), event handlers.\n */\n\n/** On any element. */\nconst DRAWN = new Set([\n // The site's CSS selects on them; SVG and anchors refer to ids.\n \"class\",\n \"style\",\n \"id\",\n // Text direction and `:lang()`.\n \"dir\",\n \"lang\",\n // `[role=…]` selectors (a keyword).\n \"role\",\n // Shadow DOM: where a child goes, `::part()`.\n \"slot\",\n \"part\",\n // `:disabled`, details and dialogs that are open.\n \"disabled\",\n \"open\",\n // Sizes and old presentational attributes.\n \"width\",\n \"height\",\n \"align\",\n \"valign\",\n \"bgcolor\",\n \"background\",\n \"border\",\n \"cellpadding\",\n \"cellspacing\",\n \"nowrap\",\n \"colspan\",\n \"rowspan\",\n \"span\",\n]);\n/** Only on some elements. */\nconst DRAWN_ON: Record<string, readonly string[]> = {\n a: [\"href\"],\n area: [\"href\"],\n img: [\"src\", \"srcset\", \"sizes\", \"alt\"],\n link: [\"rel\", \"href\", \"media\"],\n style: [\"media\"],\n slot: [\"name\"],\n ol: [\"start\", \"reversed\", \"type\"],\n ul: [\"type\"],\n li: [\"type\", \"value\"],\n button: [\"type\"],\n meter: [\"value\", \"min\", \"max\", \"low\", \"high\", \"optimum\"],\n progress: [\"value\", \"max\"],\n // A field's look; fieldAttributes picks what a field keeps.\n input: [\"type\", \"placeholder\", \"size\", \"readonly\", \"required\", \"value\"],\n textarea: [\"placeholder\", \"rows\", \"cols\", \"readonly\", \"required\"],\n select: [\"size\", \"multiple\", \"required\"],\n};\n/**\n * UI state that component libraries style with (Radix, shadcn, Headless\n * UI: open or closed, checked, the side a popover is on, the theme), kept\n * only while the value is a short keyword.\n */\nconst STATE = new Set([\n \"data-state\",\n \"data-side\",\n \"data-align\",\n \"data-orientation\",\n \"data-disabled\",\n \"data-highlighted\",\n \"data-selected\",\n \"data-active\",\n \"data-open\",\n \"data-checked\",\n \"data-slot\",\n \"data-variant\",\n \"data-size\",\n \"data-theme\",\n \"aria-expanded\",\n \"aria-selected\",\n \"aria-checked\",\n \"aria-pressed\",\n \"aria-current\",\n \"aria-disabled\",\n \"aria-hidden\",\n \"aria-invalid\",\n \"aria-busy\",\n \"aria-orientation\",\n \"aria-sort\",\n]);\nconst KEYWORD = /^[\\w-]{0,32}$/;\n/** SVG geometry and presentation (lower case; SVG keeps its case). */\nconst SVG_DRAWN = new Set([\n \"href\",\n \"xlink:href\",\n \"viewbox\",\n \"preserveaspectratio\",\n \"d\",\n \"points\",\n \"pathlength\",\n \"x\",\n \"y\",\n \"x1\",\n \"y1\",\n \"x2\",\n \"y2\",\n \"cx\",\n \"cy\",\n \"r\",\n \"rx\",\n \"ry\",\n \"dx\",\n \"dy\",\n \"fx\",\n \"fy\",\n \"fr\",\n \"rotate\",\n \"transform\",\n \"fill\",\n \"fill-opacity\",\n \"fill-rule\",\n \"stroke\",\n \"stroke-width\",\n \"stroke-linecap\",\n \"stroke-linejoin\",\n \"stroke-dasharray\",\n \"stroke-dashoffset\",\n \"stroke-miterlimit\",\n \"stroke-opacity\",\n \"opacity\",\n \"color\",\n \"display\",\n \"visibility\",\n \"overflow\",\n \"vector-effect\",\n \"paint-order\",\n \"shape-rendering\",\n \"clip-path\",\n \"clip-rule\",\n \"clippathunits\",\n \"mask\",\n \"maskunits\",\n \"maskcontentunits\",\n \"filter\",\n \"filterunits\",\n \"primitiveunits\",\n \"offset\",\n \"stop-color\",\n \"stop-opacity\",\n \"gradientunits\",\n \"gradienttransform\",\n \"spreadmethod\",\n \"patternunits\",\n \"patterncontentunits\",\n \"patterntransform\",\n \"markerwidth\",\n \"markerheight\",\n \"markerunits\",\n \"refx\",\n \"refy\",\n \"orient\",\n \"marker-start\",\n \"marker-mid\",\n \"marker-end\",\n \"text-anchor\",\n \"dominant-baseline\",\n \"alignment-baseline\",\n \"baseline-shift\",\n \"font-family\",\n \"font-size\",\n \"font-weight\",\n \"font-style\",\n \"letter-spacing\",\n \"word-spacing\",\n \"text-decoration\",\n \"textlength\",\n \"lengthadjust\",\n \"startoffset\",\n \"stddeviation\",\n \"in\",\n \"in2\",\n \"result\",\n \"values\",\n \"type\",\n \"mode\",\n \"operator\",\n \"flood-color\",\n \"flood-opacity\",\n \"lighting-color\",\n \"color-interpolation-filters\",\n \"scale\",\n]);\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n/** Inputs whose `value` is the button's label, not something typed. */\nconst LABEL_INPUTS = new Set([\"submit\", \"button\", \"reset\"]);\n\n/** Whether the copy may have this attribute of `element` at all. */\nexport function copiesAttribute(element: Element, name: string) {\n const lower = name.toLowerCase();\n if (DRAWN.has(lower) || STATE.has(lower)) return true;\n if (element.namespaceURI === SVG_NS) return SVG_DRAWN.has(lower);\n return DRAWN_ON[element.localName.toLowerCase()]?.includes(lower) ?? false;\n}\n\nconst ATTRIBUTE_NAME = /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/;\nconst EDITABLE = '[contenteditable]:not([contenteditable=\"false\"])';\n\nexport type MaskKind = \"none\" | \"drop\" | CobrowsePlaceholder;\nexport type Rendering = \"shown\" | \"box\" | \"hidden\";\n/** How an element appears in the copy, drawn or not. */\nexport type CopyKind = MaskKind | Exclude<Rendering, \"shown\">;\n\n/** Elements whose `display: none` is how they work, not concealment. */\nconst NOT_BOXES = new Set([\"html\", \"head\", \"title\", \"style\", \"link\"]);\nconst SVG_RESOURCES = new Set([\n \"defs\",\n \"symbol\",\n \"lineargradient\",\n \"radialgradient\",\n \"stop\",\n \"pattern\",\n \"clippath\",\n \"mask\",\n \"marker\",\n \"filter\",\n]);\n\n/** Whether an element is inside, or is, an editable region. */\nexport function isEditable(element: Element) {\n if ((element as HTMLElement).isContentEditable === true) return true;\n const root = element.closest(\"[contenteditable]\");\n return Boolean(root && root.getAttribute(\"contenteditable\") !== \"false\");\n}\n\n/** The resolved label of a field: its `<label>`s and `aria-labelledby`. */\nexport function fieldLabel(element: Element) {\n const parts: string[] = [];\n const labels = (element as HTMLInputElement).labels;\n if (labels) for (const label of labels) parts.push(label.textContent ?? \"\");\n for (const id of (element.getAttribute(\"aria-labelledby\") ?? \"\").split(/\\s+/))\n if (id)\n parts.push(element.ownerDocument.getElementById(id)?.textContent ?? \"\");\n return parts.join(\" \").replace(/\\s+/g, \" \").trim();\n}\n\n/** How an element appears in the copy. */\nexport function maskKind(\n element: Element,\n privateSelector: string,\n skip?: Element | null,\n): MaskKind {\n const tag = element.localName.toLowerCase();\n if (skip && element === skip) return \"drop\";\n if (DROPPED.has(tag)) return \"drop\";\n if (\n tag === \"input\" &&\n element.getAttribute(\"type\")?.toLowerCase() === \"hidden\"\n )\n return \"drop\";\n if (tag === \"link\") {\n const rel = (element.getAttribute(\"rel\") ?? \"\").toLowerCase().split(/\\s+/);\n return rel.includes(\"stylesheet\") && !rel.includes(\"alternate\")\n ? \"none\"\n : \"drop\";\n }\n try {\n if (element.matches(privateSelector)) return \"private\";\n } catch {\n /* A broken site selector: the default private marker still applies. */\n if (element.matches(\"[data-luma-private]\")) return \"private\";\n }\n if (FRAMES.has(tag)) return \"frame\";\n if (MEDIA.has(tag)) return \"media\";\n if (FIELDS.has(tag)) return \"field\";\n if (element.getAttribute(\"contenteditable\") !== null && isEditable(element))\n return \"private\";\n return \"none\";\n}\n\n/**\n * Whether an element is drawn: \"shown\", \"box\" (an empty box of its size:\n * `visibility: hidden` or `collapse`, `content-visibility: hidden`) or\n * \"hidden\" (no box at all: `display: none`, the `hidden` attribute, a\n * closed dialog, a closed details element's content, a light DOM child no\n * slot shows). The copy has the text and attributes of shown elements only.\n *\n * It is decided on the element itself, as the recorder copies from the top\n * down (an element below a box or a hidden one is not copied at all):\n * `visibility` is inherited, so the element's own computed value tells, and\n * `checkVisibility()`, where the browser has it, also knows about a\n * `display: none` above. Transparent (`opacity: 0`), clipped and off-screen\n * content is drawn, so it is copied.\n */\nexport function rendering(element: Element): Rendering {\n const tag = element.localName.toLowerCase();\n // The page's style sheets and title: not drawn, but how it is drawn.\n if (NOT_BOXES.has(tag)) return \"shown\";\n if (element.hasAttribute(\"hidden\")) return \"hidden\";\n const svg = element.namespaceURI === SVG_NS;\n // Gradients, clip paths, symbols and the like have no box of their own.\n if (svg && (SVG_RESOURCES.has(tag) || tag.startsWith(\"fe\"))) return \"shown\";\n let style: CSSStyleDeclaration | undefined;\n try {\n style = element.ownerDocument.defaultView?.getComputedStyle(element);\n } catch {\n /* No style to tell from. */\n }\n const display = style?.display;\n if (display === \"none\") return \"hidden\";\n // A `display: contents` element has no box, its children do; inside an\n // SVG, shapes in defs, symbols or clip paths have none and are still used.\n const check = (element as Element & { checkVisibility?: () => boolean })\n .checkVisibility;\n const inSvg = svg && element.parentElement?.namespaceURI === SVG_NS;\n if (\n typeof check === \"function\" &&\n display !== \"contents\" &&\n !inSvg &&\n !check.call(element)\n )\n return \"hidden\";\n const visibility = style?.visibility;\n if (visibility === \"hidden\" || visibility === \"collapse\") return \"box\";\n if (style?.getPropertyValue(\"content-visibility\") === \"hidden\") return \"box\";\n return \"shown\";\n}\n\n/** An absolute http(s) URL, or null for anything else. */\nexport function webUrl(value: string, base: string): string | null {\n const trimmed = value.trim();\n if (!trimmed) return null;\n try {\n const url = new URL(trimmed, base);\n if (url.protocol === \"http:\" || url.protocol === \"https:\") return url.href;\n if (\n url.protocol === \"data:\" &&\n /^data:image\\/(png|gif|jpe?g|webp|avif|svg\\+xml)[;,]/i.test(trimmed) &&\n trimmed.length <= COBROWSE_LIMITS.attributeChars\n )\n return trimmed;\n } catch {\n /* Not a URL. */\n }\n return null;\n}\n\n/** A link's address without query and fragment (they can carry tokens). */\nfunction linkUrl(value: string, base: string) {\n const url = webUrl(value, base);\n if (!url || url.startsWith(\"data:\")) return null;\n const parsed = new URL(url);\n return parsed.origin + parsed.pathname;\n}\n\n/** `srcset` with every candidate made absolute; unsafe candidates dropped. */\nfunction srcset(value: string, base: string) {\n return value\n .split(\",\")\n .map((candidate) => {\n const [url, ...descriptor] = candidate.trim().split(/\\s+/);\n const absolute = url ? webUrl(url, base) : null;\n return absolute && !absolute.startsWith(\"data:\")\n ? [absolute, ...descriptor].join(\" \")\n : null;\n })\n .filter(Boolean)\n .join(\", \");\n}\n\nconst CSS_URL = /url\\(\\s*(['\"]?)([^'\")]*)\\1\\s*\\)/gi;\nconst CSS_IMPORT = /@import\\s+(['\"])([^'\"]*)\\1/gi;\n\n/**\n * CSS with every `url()` and `@import` made absolute against `base`; a URL\n * that is not a web or image address becomes `url()` (nothing).\n */\nexport function absoluteCss(css: string, base: string) {\n return css\n .replace(CSS_URL, (_match, _quote: string, url: string) => {\n if (url.startsWith(\"#\")) return `url(\"${url}\")`;\n const absolute = webUrl(url, base);\n return absolute ? `url(\"${absolute.replace(/\"/g, \"%22\")}\")` : \"url()\";\n })\n .replace(CSS_IMPORT, (_match, _quote: string, url: string) => {\n const absolute = webUrl(url, base);\n return absolute ? `@import \"${absolute.replace(/\"/g, \"%22\")}\"` : \"\";\n });\n}\n\n/**\n * The attributes the copy may have (the allowlist above): never an event\n * handler, a value but a drawn one, a non-web URL; links without their\n * query.\n */\nexport function copyAttributes(element: Element, base: string) {\n const tag = element.localName.toLowerCase();\n const type = (element.getAttribute(\"type\") ?? \"\").toLowerCase();\n const attributes: Record<string, string> = {};\n for (const attribute of element.attributes) {\n const name = attribute.name.toLowerCase();\n let value = attribute.value;\n if (!ATTRIBUTE_NAME.test(attribute.name)) continue;\n if (!copiesAttribute(element, name)) continue;\n if (value.length > COBROWSE_LIMITS.attributeChars) continue;\n if ((STATE.has(name) || name === \"role\") && !KEYWORD.test(value.trim()))\n continue;\n // A button's label stays; anything a field holds never does.\n if (name === \"value\" && tag === \"input\" && !LABEL_INPUTS.has(type))\n continue;\n if (name === \"style\") value = absoluteCss(value, base);\n else if (name === \"srcset\") {\n value = srcset(value, base);\n if (!value) continue;\n } else if (URL_ATTRIBUTES.has(name)) {\n if (value.trim().startsWith(\"#\")) {\n attributes[attribute.name] = value.trim();\n continue;\n }\n // An SVG <use> refers to its own document only.\n if (tag === \"use\") continue;\n const url =\n (tag === \"a\" || tag === \"area\") && name.endsWith(\"href\")\n ? linkUrl(value, base)\n : webUrl(value, base);\n if (!url) continue;\n value = url;\n }\n attributes[attribute.name] = value;\n }\n return attributes;\n}\n\n/** Attributes a field keeps: how it looks, never what it holds. */\nconst FIELD_ATTRIBUTES = [\n \"class\",\n \"style\",\n \"type\",\n \"placeholder\",\n \"rows\",\n \"cols\",\n \"size\",\n \"disabled\",\n \"readonly\",\n \"dir\",\n \"lang\",\n \"role\",\n \"id\",\n \"multiple\",\n \"required\",\n];\n\n/**\n * A field's attributes. A password, payment or one-time-code field keeps\n * only its look (class, style, a neutral type), not even a placeholder.\n */\nexport function fieldAttributes(element: Element, base: string) {\n const sensitive = isSensitiveField(element, fieldLabel(element));\n const all = copyAttributes(element, base);\n const kept: Record<string, string> = {};\n for (const name of sensitive\n ? [\"class\", \"style\", \"disabled\"]\n : FIELD_ATTRIBUTES)\n if (all[name] !== undefined) kept[name] = all[name];\n const type = (element.getAttribute(\"type\") ?? \"\").toLowerCase();\n if (element.localName === \"input\")\n kept.type = sensitive\n ? type === \"password\"\n ? \"password\"\n : \"text\"\n : BUTTON_INPUTS.has(type) || !type\n ? type || \"text\"\n : type;\n // Buttons keep their label (copyAttributes kept `value` for them).\n if (!sensitive && all.value !== undefined) kept.value = all.value;\n return { attributes: kept, sensitive };\n}\n\n/** A masked region: an empty box of its size, with its look. */\nexport function placeholderAttributes(element: Element, base: string) {\n const all = copyAttributes(element, base);\n const kept: Record<string, string> = {};\n for (const name of [\"class\", \"style\", \"dir\", \"id\"])\n if (all[name] !== undefined) kept[name] = all[name];\n const rect = element.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0)\n kept.style = `${kept.style ? `${kept.style};` : \"\"}width:${Math.round(rect.width)}px;height:${Math.round(rect.height)}px`;\n return kept;\n}\n\nexport { EDITABLE };\n","import {\n COBROWSE_LIMITS,\n type CobrowseArea,\n type CobrowseChild,\n type CobrowseEndReason,\n type CobrowseFrame,\n type CobrowseNode,\n type CobrowseScroll,\n} from \"@luma/assistant-contract/cobrowse-basics\";\nimport {\n absoluteCss,\n copiesAttribute,\n copyAttributes,\n type CopyKind,\n EDITABLE,\n fieldAttributes,\n maskKind,\n placeholderAttributes,\n rendering,\n} from \"./mask\";\n\n/**\n * The co-browsing recorder (phase 14): a copy of the page's structure and\n * text, sent as a snapshot and then as batches of changes, with every\n * masking rule of ./mask.ts applied before anything leaves the browser.\n * It never reads a field's value, never listens to typing, and never takes\n * a picture of the page.\n *\n * A changed child list is sent whole: children the copy has are named by\n * id (`{ r }`), new ones are copied, and the rest are gone. That covers\n * inserts, removals and moves in any order without positions.\n *\n * Only what the page draws is copied (`rendering` in ./mask.ts): an element\n * that is not rendered is an empty, hidden element in the copy, one with\n * `visibility: hidden` an empty box of its size. Whether an element is drawn\n * can change without a change to it, so every batch checks again, against\n * the copy, the elements at and under each change (an attribute, a child\n * list, a text's element, a popover or details element that toggled), and\n * the whole page when a style sheet or the viewport changed (a media\n * query); an element whose answer changed is copied again.\n *\n * Not seen until one of those happens: what `:hover`, `:focus`, `:checked`,\n * `:defined` or `:has()` rules, animations, transitions or a style sheet\n * `<link>` that loads late show or hide. An element they show stays empty in the copy\n * until then; one they hide keeps what was sent while it was drawn, and a\n * change inside it is checked at its own element first (where the browser\n * has `checkVisibility()`, that sees a `display: none` above too).\n */\n\nconst HEAD_KEPT = new Set([\"title\", \"style\", \"link\"]);\n/** A copied element that is not drawn: no text, no attributes of its own. */\nconst HIDDEN = { style: \"display:none!important\" };\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nexport type SendResult = boolean | \"refused\";\n\nconst encoder = new TextEncoder();\n/** A frame's size on the wire: its JSON in UTF-8 (Persian text is 2 bytes a letter). */\nexport function frameBytes(frame: unknown) {\n return encoder.encode(JSON.stringify(frame)).length;\n}\n\nexport type RecorderOptions = {\n document: Document;\n /** The site's private regions (`data-luma-private` and its own). */\n privateSelector: string;\n /** The widget's own host element: never copied. */\n skip?: Element | null;\n /** The page is one the site marks restricted: nothing of it is sent. */\n restricted?: () => boolean;\n /** Sends one frame: false when it did not arrive (a snapshot follows). */\n send: (frame: CobrowseFrame) => Promise<SendResult>;\n /** Co-browsing had to stop: too big, too busy, refused by the server. */\n onLimit: (reason: CobrowseEndReason) => void;\n /** The page is busy and sending slowed down, or is back to normal. */\n onSlow?: (slow: boolean) => void;\n /** What the widget covers on the screen (its open panel, its launcher). */\n areas?: () => CobrowseArea[];\n now?: () => number;\n};\n\ntype Parent = Element | ShadowRoot;\ntype ElementCopy = Extract<CobrowseNode, { t: string }> & { si?: number };\n\nexport class Recorder {\n /** This page load; support's cursor names its node ids with it. */\n readonly page = crypto.randomUUID().replaceAll(\"-\", \"\").slice(0, 16);\n private ids = new WeakMap<Node, number>();\n private readonly nodes = new Map<number, Node>();\n private kinds = new WeakMap<Element, CopyKind>();\n private readonly styles = new Map<HTMLStyleElement, number>();\n /** Open shadow roots copied, so their private regions are checked too. */\n private readonly shadows = new Set<ShadowRoot>();\n private next = 1;\n private count = 0;\n private bytes = 0;\n private tooBig = false;\n private readonly options: RecorderOptions;\n private readonly doc: Document;\n private observer: MutationObserver | null = null;\n private records: MutationRecord[] = [];\n private scrolled = new Set<number>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private keepAlive: ReturnType<typeof setTimeout> | null = null;\n private sending = false;\n private needSnapshot = true;\n private seq = 0;\n private lastSent = 0;\n private sentLog: Array<[number, number]> = [];\n private slow = false;\n private stopped = false;\n private viewport = { w: 0, h: 0 };\n private url = \"\";\n private title = \"\";\n private adoptedCount = 0;\n private adoptedId = 0;\n /** The constructed sheets' node is in the copy. */\n private adoptedSent = false;\n private wasRestricted = false;\n /** Sends that failed in a row (the wait before the next one grows). */\n private failures = 0;\n /** The widget's areas as last sent (a signature), and their check. */\n private areasSent = \"\";\n private areaCheck: ReturnType<typeof setInterval> | null = null;\n private readonly onScroll = (event: Event) => {\n const target = event.target;\n if (target === this.doc || target === this.doc.documentElement)\n this.scrolled.add(0);\n else if (target instanceof Element) {\n const id = this.ids.get(target);\n if (id) this.scrolled.add(id);\n }\n this.schedule();\n };\n private readonly onResize = () => this.schedule();\n /** Popovers and details elements that opened or closed (a popover's\n * opening is no mutation). */\n private readonly toggled = new Set<Element>();\n private readonly onToggle = (event: Event) => {\n if (event.target instanceof Element) this.toggled.add(event.target);\n this.schedule();\n };\n\n constructor(options: RecorderOptions) {\n this.options = options;\n this.doc = options.document;\n }\n\n private get now() {\n return this.options.now?.() ?? Date.now();\n }\n\n /** The live node an id names (for support's cursor), or null. */\n node(id: number) {\n const node = this.nodes.get(id);\n return node?.isConnected ? node : null;\n }\n\n private id(node: Node) {\n let id = this.ids.get(node);\n if (!id) {\n id = this.next++;\n this.ids.set(node, id);\n }\n this.nodes.set(id, node);\n return id;\n }\n\n private known(node: Node) {\n const id = this.ids.get(node);\n return id !== undefined && this.nodes.get(id) === node;\n }\n\n private forget(node: Node) {\n const id = this.ids.get(node);\n if (id !== undefined) {\n this.nodes.delete(id);\n this.ids.delete(node);\n }\n if (node instanceof Element) {\n this.kinds.delete(node);\n if (node instanceof HTMLStyleElement) this.styles.delete(node);\n const shadow = (node as HTMLElement).shadowRoot;\n if (shadow) this.forget(shadow);\n }\n for (const child of node.childNodes) this.forget(child);\n }\n\n /** The copy of `node`, or null when it is not copied at all. */\n serialize(node: Node, inSvg = false): CobrowseNode | null {\n if (this.tooBig) return null;\n if (this.known(node)) this.forget(node);\n if (node.nodeType === 3) {\n if (++this.count > COBROWSE_LIMITS.maxNodes) {\n this.tooBig = true;\n return null;\n }\n const x = (node as Text).data.slice(0, COBROWSE_LIMITS.textChars);\n this.bytes += x.length + 14;\n return { i: this.id(node), x };\n }\n if (node.nodeType !== 1) return null;\n const element = node as Element;\n const tag = element.localName.toLowerCase();\n const parent = element.parentNode;\n if (\n parent instanceof Element &&\n parent.localName === \"head\" &&\n !HEAD_KEPT.has(tag)\n )\n return null;\n const kind = this.kindNow(element);\n if (kind === \"drop\") return null;\n if (++this.count > COBROWSE_LIMITS.maxNodes) {\n this.tooBig = true;\n return null;\n }\n this.kinds.set(element, kind);\n const svg = inSvg || element.namespaceURI === SVG_NS;\n const base = this.doc.baseURI;\n const out: ElementCopy = { i: this.id(element), t: tag };\n if (svg && !inSvg) out.svg = 1;\n if (kind !== \"none\") {\n if (kind === \"hidden\") out.a = { ...HIDDEN };\n else if (kind === \"box\") out.a = placeholderAttributes(element, base);\n else {\n out.p = kind;\n out.a =\n kind === \"field\"\n ? fieldAttributes(element, base).attributes\n : placeholderAttributes(element, base);\n }\n this.bytes += JSON.stringify(out).length;\n return out;\n }\n const attributes = copyAttributes(element, base);\n if (Object.keys(attributes).length) out.a = attributes;\n this.bytes += JSON.stringify(out).length;\n if (tag === \"style\") {\n out.css = this.styleText(element as HTMLStyleElement);\n this.bytes += out.css.length;\n return out;\n }\n // A foreignObject holds HTML again.\n const children = this.children(element, svg && tag !== \"foreignobject\");\n if (tag === \"head\") {\n const adopted = this.adoptedNode();\n if (adopted) children.push(adopted);\n }\n if (children.length) out.c = children;\n const shadow = (element as HTMLElement).shadowRoot;\n if (shadow) {\n out.si = this.id(shadow);\n out.sh = this.children(shadow, false);\n this.shadows.add(shadow);\n this.observe(shadow);\n }\n if (element.scrollTop || element.scrollLeft) this.scrolled.add(out.i);\n return out;\n }\n\n private children(parent: Parent, inSvg: boolean) {\n const list: CobrowseNode[] = [];\n for (const child of parent.childNodes) {\n const copy = this.serialize(child, inSvg);\n if (copy) list.push(copy);\n }\n return list;\n }\n\n /** A style element's rules as the page has them (CSS-in-JS included). */\n private styleText(style: HTMLStyleElement) {\n let css = \"\";\n try {\n const rules = style.sheet?.cssRules;\n if (rules?.length)\n css = Array.from(rules, (rule) => rule.cssText).join(\"\\n\");\n this.styles.set(style, rules?.length ?? 0);\n } catch {\n this.styles.set(style, 0);\n }\n if (!css) css = style.textContent ?? \"\";\n return absoluteCss(css, this.doc.baseURI).slice(\n 0,\n COBROWSE_LIMITS.cssChars,\n );\n }\n\n private adoptedSheets() {\n return (\n (this.doc as Document & { adoptedStyleSheets?: CSSStyleSheet[] })\n .adoptedStyleSheets ?? []\n );\n }\n\n private adoptedRuleCount() {\n let count = 0;\n for (const sheet of this.adoptedSheets())\n try {\n count += sheet.cssRules.length;\n } catch {\n /* unreadable */\n }\n return count;\n }\n\n /** The document's constructed style sheets, as one style element. */\n private adoptedNode(): ElementCopy | null {\n const sheets = this.adoptedSheets();\n this.adoptedCount = this.adoptedRuleCount();\n if (!sheets.length) return null;\n let css = \"\";\n for (const sheet of sheets)\n try {\n css += Array.from(sheet.cssRules, (rule) => rule.cssText).join(\"\\n\");\n } catch {\n /* unreadable */\n }\n this.adoptedId ||= this.next++;\n this.adoptedSent = true;\n return {\n i: this.adoptedId,\n t: \"style\",\n css: absoluteCss(css, this.doc.baseURI).slice(\n 0,\n COBROWSE_LIMITS.cssChars,\n ),\n };\n }\n\n private observe(target: Node) {\n this.observer?.observe(target, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n }\n\n private scrollOf(id: number): CobrowseScroll | null {\n if (id === 0) {\n const view = this.doc.defaultView;\n return [\n 0,\n Math.round(view?.scrollX ?? 0),\n Math.round(view?.scrollY ?? 0),\n ];\n }\n const node = this.nodes.get(id);\n if (!(node instanceof Element) || !node.isConnected) return null;\n return [id, Math.round(node.scrollLeft), Math.round(node.scrollTop)];\n }\n\n private readViewport() {\n const view = this.doc.defaultView;\n return {\n w: Math.max(1, Math.round(view?.innerWidth ?? 1)),\n h: Math.max(1, Math.round(view?.innerHeight ?? 1)),\n };\n }\n\n private pageUrl() {\n const location = this.doc.location;\n return location ? location.origin + location.pathname : \"\";\n }\n\n /** The whole page: a snapshot frame, or null when it is too big. */\n snapshot(): Extract<CobrowseFrame, { type: \"snapshot\" }> | null {\n this.count = 0;\n this.bytes = 0;\n this.tooBig = false;\n this.ids = new WeakMap();\n this.kinds = new WeakMap();\n this.nodes.clear();\n this.styles.clear();\n this.shadows.clear();\n this.scrolled = new Set([0]);\n this.adoptedId = 0;\n this.adoptedSent = false;\n this.observer?.disconnect();\n this.observer = new MutationObserver((records) => {\n this.records.push(...records);\n this.schedule();\n });\n this.observe(this.doc);\n const root = this.serialize(this.doc.documentElement);\n this.records = [];\n if (!root || this.tooBig || this.bytes > COBROWSE_LIMITS.snapshotBytes)\n return null;\n this.viewport = this.readViewport();\n this.url = this.pageUrl();\n this.title = this.doc.title.slice(0, 300);\n const scrolls = [...this.scrolled]\n .map((id) => this.scrollOf(id))\n .filter((item): item is CobrowseScroll => item !== null);\n this.scrolled.clear();\n const frame: Extract<CobrowseFrame, { type: \"snapshot\" }> = {\n type: \"snapshot\",\n page: this.page,\n url: this.url,\n title: this.title,\n origin: this.doc.location?.origin ?? \"\",\n viewport: this.viewport,\n root,\n scrolls,\n bytes: 0,\n // The next change batch is seq + 1: the owner's view sees a gap.\n seq: this.seq,\n ...this.widgetAreas(true),\n };\n // The count above is a quick estimate; the limit holds for what is sent.\n frame.bytes = frameBytes(frame);\n return frame.bytes > COBROWSE_LIMITS.snapshotBytes ? null : frame;\n }\n\n /**\n * The widget's areas for a frame: always in a snapshot, in a change\n * batch only when they moved (the panel opened, closed or resized).\n */\n private widgetAreas(always: boolean): { widget?: CobrowseArea[] } {\n if (!this.options.areas) return {};\n const areas = this.options.areas();\n const signature = JSON.stringify(areas);\n if (!always && signature === this.areasSent) return {};\n this.areasSent = signature;\n return { widget: areas };\n }\n\n /**\n * Whether a node sits inside something the copy keeps empty, or outside\n * the copy: below an element that was never copied (a script, a dropped\n * head element) a node that was copied elsewhere before is not sent.\n */\n private masked(node: Node) {\n let current: Node | null = node.parentNode;\n while (current) {\n if (current instanceof Element) {\n if (!this.known(current)) return true;\n const kind = this.kinds.get(current);\n if (kind && kind !== \"none\") return true;\n const tag = current.localName;\n if (tag === \"textarea\" || tag === \"select\") return true;\n current = current.parentNode;\n } else if (current instanceof ShadowRoot) {\n if (!this.known(current)) return true;\n current = current.host;\n } else current = current.parentNode;\n }\n return false;\n }\n\n /** How an element is copied now: masked, not drawn, or as it is. */\n private kindNow(element: Element): CopyKind {\n const kind = maskKind(\n element,\n this.options.privateSelector,\n this.options.skip,\n );\n if (kind === \"drop\") return kind;\n const drawn = rendering(element);\n return drawn === \"shown\" ? kind : drawn;\n }\n\n /**\n * Copies again every element at or under `roots` whose copy no longer\n * matches the page (it became hidden or shown, private or not), each\n * element checked once a batch.\n */\n private recheck(\n roots: Iterable<Element | ShadowRoot>,\n remask: (element: Element) => void,\n ) {\n const seen = new Set<Node>();\n const stack = [...roots];\n while (stack.length) {\n const node = stack.pop()!;\n if (seen.has(node) || !this.known(node) || !node.isConnected) continue;\n seen.add(node);\n if (node instanceof Element) {\n const kind = this.kinds.get(node);\n if (kind === undefined) continue;\n if (this.kindNow(node) !== kind) {\n remask(node);\n continue;\n }\n // Nothing under a masked or hidden element is in the copy.\n if (kind !== \"none\") continue;\n const shadow = (node as HTMLElement).shadowRoot;\n if (shadow) stack.push(shadow);\n }\n for (const child of node.children) stack.push(child);\n }\n }\n\n /**\n * Every element that must be copied empty now, in the document and in\n * every open shadow root copied (a selector can start to match after a\n * class, an attribute or a child changes, `:has()` included).\n */\n private maskedNow() {\n const editable = `${EDITABLE},[data-luma-private]`;\n const found: Element[] = [];\n const scopes: Array<Document | ShadowRoot> = [this.doc];\n for (const shadow of this.shadows)\n if (shadow.host.isConnected) scopes.push(shadow);\n else this.shadows.delete(shadow);\n for (const scope of scopes)\n try {\n found.push(\n ...scope.querySelectorAll(\n `${this.options.privateSelector},${editable}`,\n ),\n );\n } catch {\n found.push(...scope.querySelectorAll(editable));\n }\n return found;\n }\n\n /** The changes since the last frame, or null when nothing changed. */\n changes(): Extract<CobrowseFrame, { type: \"changes\" }> | null {\n const records = [...this.records, ...(this.observer?.takeRecords() ?? [])];\n this.records = [];\n const lists = new Set<Parent>();\n const attrs = new Set<Element>();\n /** Elements with a change to an attribute the copy has. */\n const copied = new Set<Element>();\n const texts = new Set<Text>();\n const css = new Set<HTMLStyleElement>();\n const removed: Node[] = [];\n for (const record of records) {\n const target = record.target;\n if (record.type === \"childList\") {\n if (target instanceof HTMLStyleElement) css.add(target);\n else if (target instanceof Element || target instanceof ShadowRoot)\n lists.add(target);\n removed.push(...record.removedNodes);\n } else if (record.type === \"attributes\" && target instanceof Element) {\n attrs.add(target);\n if (\n record.attributeName &&\n copiesAttribute(target, record.attributeName)\n )\n copied.add(target);\n } else if (record.type === \"characterData\") {\n const parent = target.parentNode;\n if (parent instanceof HTMLStyleElement) css.add(parent);\n else if (target instanceof Text) texts.add(target);\n }\n }\n for (const [style, count] of this.styles)\n try {\n if ((style.sheet?.cssRules.length ?? 0) !== count) css.add(style);\n } catch {\n /* unreadable */\n }\n const viewport = this.readViewport();\n const resized =\n viewport.w !== this.viewport.w || viewport.h !== this.viewport.h;\n\n // Masking first: an element that became private, editable or hidden\n // (by its own change, a class change above it, a style sheet) is\n // copied again, empty, before any text inside it could be sent; one\n // that became drawn is copied again with its content.\n const remask = (element: Element) => {\n const parent = element.parentNode;\n this.forget(element);\n if (parent instanceof Element || parent instanceof ShadowRoot)\n lists.add(parent);\n };\n const toggled = [...this.toggled];\n this.toggled.clear();\n const head = this.doc.head;\n const restyled =\n css.size > 0 ||\n resized ||\n (head !== null && lists.has(head)) ||\n (this.adoptedId !== 0 && this.adoptedRuleCount() !== this.adoptedCount);\n const roots: Array<Element | ShadowRoot> = restyled\n ? [this.doc.documentElement, ...this.shadows]\n : [...attrs, ...lists, ...toggled];\n if (!restyled)\n for (const text of texts)\n if (text.parentNode instanceof Element) roots.push(text.parentNode);\n this.recheck(roots, remask);\n if (records.length)\n for (const element of this.maskedNow())\n if (this.known(element) && this.kinds.get(element) === \"none\")\n remask(element);\n\n this.count = this.nodes.size;\n this.bytes = 0;\n const frame: Extract<CobrowseFrame, { type: \"changes\" }> = {\n type: \"changes\",\n page: this.page,\n seq: this.seq + 1,\n };\n const listOut: Array<{ i: number; c: CobrowseChild[] }> = [];\n for (const parent of lists) {\n const host = parent instanceof ShadowRoot ? parent.host : parent;\n if (!this.known(parent) || !host.isConnected || this.masked(host))\n continue;\n if (parent instanceof Element) {\n const kind = this.kinds.get(parent);\n if ((kind && kind !== \"none\") || parent.localName === \"style\") continue;\n }\n const inSvg =\n parent instanceof Element &&\n parent.namespaceURI === SVG_NS &&\n parent.localName.toLowerCase() !== \"foreignobject\";\n const children: CobrowseChild[] = [];\n for (const child of parent.childNodes) {\n if (this.known(child)) children.push({ r: this.ids.get(child)! });\n else {\n const copy = this.serialize(child, inSvg);\n if (copy) children.push(copy);\n }\n }\n if (parent instanceof Element && parent.localName === \"head\") {\n // The copy has the constructed sheets already; changes to them go\n // as `css`.\n if (this.adoptedId && this.adoptedSent)\n children.push({ r: this.adoptedId });\n else {\n const adopted = this.adoptedNode();\n if (adopted) children.push(adopted);\n }\n }\n listOut.push({ i: this.ids.get(parent)!, c: children });\n }\n if (this.tooBig) return null;\n for (const node of removed)\n if (!node.isConnected && this.known(node)) this.forget(node);\n if (listOut.length) frame.lists = listOut;\n\n const base = this.doc.baseURI;\n const attrOut: Array<{ i: number; a: Record<string, string> }> = [];\n for (const element of copied) {\n if (!this.known(element) || !element.isConnected || this.masked(element))\n continue;\n const kind = this.kinds.get(element);\n if (kind === \"hidden\") continue;\n attrOut.push({\n i: this.ids.get(element)!,\n a:\n kind === \"field\"\n ? fieldAttributes(element, base).attributes\n : kind && kind !== \"none\"\n ? placeholderAttributes(element, base)\n : copyAttributes(element, base),\n });\n }\n if (attrOut.length) frame.attrs = attrOut;\n\n const textOut: Array<{ i: number; x: string }> = [];\n for (const text of texts)\n if (this.known(text) && text.isConnected && !this.masked(text))\n textOut.push({\n i: this.ids.get(text)!,\n x: text.data.slice(0, COBROWSE_LIMITS.textChars),\n });\n if (textOut.length) frame.texts = textOut;\n\n const cssOut: Array<{ i: number; css: string }> = [];\n for (const style of css)\n if (this.known(style) && style.isConnected && !this.masked(style))\n cssOut.push({ i: this.ids.get(style)!, css: this.styleText(style) });\n if (this.adoptedId && this.adoptedRuleCount() !== this.adoptedCount) {\n const adopted = this.adoptedNode();\n if (adopted?.css !== undefined)\n cssOut.push({ i: this.adoptedId, css: adopted.css });\n }\n if (cssOut.length) frame.css = cssOut;\n\n const scrolls = [...this.scrolled]\n .map((id) => this.scrollOf(id))\n .filter((item): item is CobrowseScroll => item !== null);\n this.scrolled.clear();\n if (scrolls.length) frame.scrolls = scrolls;\n if (resized) {\n this.viewport = viewport;\n frame.viewport = viewport;\n }\n const url = this.pageUrl();\n if (url !== this.url) {\n this.url = url;\n frame.url = url;\n }\n const title = this.doc.title.slice(0, 300);\n if (title !== this.title) {\n this.title = title;\n frame.title = title;\n }\n Object.assign(frame, this.widgetAreas(false));\n if (Object.keys(frame).length <= 3) return null;\n this.seq = frame.seq;\n return frame;\n }\n\n /** Whether something changed that no mutation record reports. */\n private quietChange() {\n // Into or out of a restricted page, even back to the same address.\n if ((this.options.restricted?.() ?? false) !== this.wasRestricted)\n return true;\n // A resize while a frame was on its way (its event found nothing to do).\n const viewport = this.readViewport();\n if (viewport.w !== this.viewport.w || viewport.h !== this.viewport.h)\n return true;\n if (this.pageUrl() !== this.url) return true;\n if (this.doc.title.slice(0, 300) !== this.title) return true;\n for (const [style, count] of this.styles)\n try {\n if ((style.sheet?.cssRules.length ?? 0) !== count) return true;\n } catch {\n /* unreadable */\n }\n if (this.adoptedId && this.adoptedRuleCount() !== this.adoptedCount)\n return true;\n return Boolean(\n this.options.areas &&\n JSON.stringify(this.options.areas()) !== this.areasSent,\n );\n }\n\n /** Whether the last snapshot or change ran past the node limit. */\n get overLimit() {\n return this.tooBig;\n }\n\n // ------------------------------------------------------------- sending\n\n /** Starts sending: the snapshot, then changes as they happen. */\n start() {\n this.doc.addEventListener(\"scroll\", this.onScroll, {\n capture: true,\n passive: true,\n });\n this.doc.defaultView?.addEventListener(\"resize\", this.onResize);\n this.doc.addEventListener(\"toggle\", this.onToggle, { capture: true });\n // What changes without a DOM mutation (a route by pushState, rules\n // added through the CSSOM, the widget's panel opening or resizing):\n // checked twice a second, a batch sent only when something differs.\n this.areaCheck = setInterval(() => {\n if (this.quietChange()) this.schedule();\n }, 500);\n this.needSnapshot = true;\n this.schedule(0);\n }\n\n /** A fresh snapshot goes out next (the owner's view asked for one). */\n resync() {\n this.needSnapshot = true;\n this.schedule(0);\n }\n\n /** Stops observing and sending, for good. */\n destroy() {\n this.stopped = true;\n if (this.timer) clearTimeout(this.timer);\n if (this.keepAlive) clearTimeout(this.keepAlive);\n this.timer = null;\n this.keepAlive = null;\n if (this.areaCheck) clearInterval(this.areaCheck);\n this.areaCheck = null;\n this.observer?.disconnect();\n this.observer = null;\n this.records = [];\n this.doc.removeEventListener(\"scroll\", this.onScroll, { capture: true });\n this.doc.defaultView?.removeEventListener(\"resize\", this.onResize);\n this.doc.removeEventListener(\"toggle\", this.onToggle, { capture: true });\n this.toggled.clear();\n }\n\n /** Bytes sent in the last minute. */\n minuteBytes() {\n const since = this.now - 60_000;\n this.sentLog = this.sentLog.filter(([at]) => at >= since);\n return this.sentLog.reduce((sum, [, bytes]) => sum + bytes, 0);\n }\n\n private schedule(delay?: number) {\n // While a frame is on its way, the send's own end schedules the next.\n if (this.stopped || this.timer || this.sending) return;\n const gap = this.slow\n ? COBROWSE_LIMITS.slowFlushMs\n : COBROWSE_LIMITS.flushMs;\n const wait = delay ?? Math.max(0, gap - (this.now - this.lastSent));\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, wait);\n }\n\n private nextFrame(): CobrowseFrame | null | \"too_big\" {\n // A single-page app can route into, and out of, a restricted page.\n const restricted = this.options.restricted?.() ?? false;\n if (restricted !== this.wasRestricted) {\n this.wasRestricted = restricted;\n this.needSnapshot = true;\n }\n if (restricted) {\n this.records = [];\n this.observer?.takeRecords();\n this.scrolled.clear();\n return this.needSnapshot\n ? {\n type: \"restricted\",\n page: this.page,\n url: this.doc.location?.origin ?? \"\",\n }\n : null;\n }\n if (this.needSnapshot) return this.snapshot() ?? \"too_big\";\n const changes = this.changes();\n if (changes === null && this.tooBig) return \"too_big\";\n if (changes && frameBytes(changes) > COBROWSE_LIMITS.batchBytes)\n // A big change goes out as a fresh copy instead.\n return this.snapshot() ?? \"too_big\";\n return changes;\n }\n\n private async flush() {\n if (this.stopped) return;\n if (this.sending) return;\n const frame = this.nextFrame();\n if (frame === \"too_big\") {\n this.end(\"too_big\");\n return;\n }\n if (frame === null) {\n this.armKeepAlive();\n return;\n }\n let size = frameBytes(frame);\n const used = this.minuteBytes() + size;\n if (used > COBROWSE_LIMITS.minuteBytes) {\n this.end(\"busy\");\n return;\n }\n const slow = used > COBROWSE_LIMITS.slowMinuteBytes;\n if (slow !== this.slow) {\n this.slow = slow;\n this.options.onSlow?.(slow);\n if (frame.type === \"changes\") {\n frame.slow = slow;\n size = frameBytes(frame);\n }\n }\n this.sending = true;\n this.needSnapshot = false;\n const sentAt = this.now;\n const result = await this.options.send(frame);\n this.sending = false;\n if (this.stopped) return;\n if (result === \"refused\") {\n this.end(\"refused\");\n return;\n }\n this.lastSent = sentAt;\n if (!result) {\n // Lost on the way (the network, the server): the next frame is a\n // whole copy again, after a growing wait so an outage is not flooded.\n this.needSnapshot = true;\n this.failures += 1;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.schedule(\n Math.min(\n COBROWSE_LIMITS.keepAliveMs,\n COBROWSE_LIMITS.slowFlushMs * 2 ** (this.failures - 1),\n ),\n );\n this.armKeepAlive();\n return;\n }\n this.failures = 0;\n this.sentLog.push([sentAt, size]);\n if (this.needSnapshot || this.records.length || this.scrolled.size)\n this.schedule();\n this.armKeepAlive();\n }\n\n private armKeepAlive() {\n if (this.keepAlive) clearTimeout(this.keepAlive);\n this.keepAlive = setTimeout(() => {\n this.keepAlive = null;\n if (this.stopped) return;\n if (!this.sending)\n void this.options\n .send({ type: \"alive\", page: this.page })\n .then((result) => {\n if (result === \"refused\") this.end(\"refused\");\n });\n this.armKeepAlive();\n }, COBROWSE_LIMITS.keepAliveMs);\n }\n\n private end(reason: CobrowseEndReason) {\n if (this.stopped) return;\n this.destroy();\n this.options.onLimit(reason);\n }\n}\n","// The co-browsing module (phase 14): the recorder and support's cursor.\n// The widget starts the session with the server first. Built on its own (assets/cobrowse.js) or split into its own chunk by the\n// package, and loaded by the widget only when the visitor allows support to\n// see the page, so a site that never co-browses never downloads it.\nimport {\n type CobrowseAnchor,\n type CobrowseArea,\n type CobrowseCommand,\n type CobrowseEndReason,\n type CobrowseFrame,\n pointOf,\n} from \"@luma/assistant-contract/cobrowse-basics\";\nimport { Recorder, type SendResult } from \"./recorder\";\nimport { createSupportCursor, type CursorTarget } from \"./support-cursor\";\n\nexport type CobrowseOptions = {\n lang: \"fa\" | \"en\";\n /** The widget's own layer for support's cursor (in its shadow root). */\n layer: HTMLElement;\n /** The widget's host element: never copied. */\n skip: Element | null;\n privateSelector: string;\n /** The page is one the site marks restricted: only that is said. */\n restricted: () => boolean;\n send: (frame: CobrowseFrame) => Promise<SendResult>;\n /** It stopped by itself (too big, too busy, refused). */\n onEnd: (reason: CobrowseEndReason) => void;\n onSlow?: (slow: boolean) => void;\n};\n\nexport type CobrowseHandle = {\n command: (command: CobrowseCommand) => void;\n /** The visitor (or the widget) ends it: the owner is told. */\n stop: (reason: CobrowseEndReason) => void;\n /** Ends without telling anyone (the server already ended it). */\n destroy: () => void;\n};\n\n/** The box of a live node: an element's, or a text node's text. */\nexport function nodeRect(node: Node | null): DOMRect | null {\n if (!node?.isConnected) return null;\n if (node instanceof Element) return node.getBoundingClientRect();\n if (node.nodeType === 3) {\n const range = node.ownerDocument?.createRange();\n if (!range) return null;\n range.selectNodeContents(node);\n return range.getBoundingClientRect();\n }\n return null;\n}\n\n/** Where an anchor points on this page now, or null (another page). */\nexport function anchorTarget(\n recorder: Pick<Recorder, \"page\" | \"node\">,\n at: CobrowseAnchor,\n): CursorTarget {\n return () => {\n if (\"screen\" in at || at.page !== recorder.page) return null;\n const rect = nodeRect(recorder.node(at.node));\n if (!rect || (rect.width === 0 && rect.height === 0)) return null;\n return pointOf(rect, at.fx, at.fy);\n };\n}\n\n/**\n * What the widget covers on the visitor's screen: its open panel and its\n * launcher (marked `data-luma-widget-area` in its shadow root), as boxes\n * of the viewport. A closed (hidden) panel covers nothing.\n */\nexport function widgetAreas(layer: HTMLElement): CobrowseArea[] {\n const root = layer.getRootNode() as Document | ShadowRoot;\n const areas: CobrowseArea[] = [];\n for (const element of root.querySelectorAll(\"[data-luma-widget-area]\")) {\n const kind = element.getAttribute(\"data-luma-widget-area\");\n if (kind !== \"panel\" && kind !== \"launcher\") continue;\n const style = getComputedStyle(element);\n if (\n style.display === \"none\" ||\n style.visibility === \"hidden\" ||\n Number(style.opacity) < 0.1\n )\n continue;\n const rect = element.getBoundingClientRect();\n if (rect.width < 1 || rect.height < 1) continue;\n areas.push({\n kind,\n x: Math.round(rect.left),\n y: Math.round(rect.top),\n w: Math.round(rect.width),\n h: Math.round(rect.height),\n });\n }\n return areas.slice(0, 4);\n}\n\nexport function startCobrowse(options: CobrowseOptions): CobrowseHandle {\n let ended = false;\n const cursor = createSupportCursor(options.layer, options.lang);\n const recorder = new Recorder({\n document,\n privateSelector: options.privateSelector,\n skip: options.skip,\n restricted: options.restricted,\n send: options.send,\n onSlow: options.onSlow,\n areas: () => widgetAreas(options.layer),\n onLimit: (reason) => {\n if (ended) return;\n ended = true;\n cursor.destroy();\n void options.send({ type: \"end\", reason });\n options.onEnd(reason);\n },\n });\n // The widget has started the session with the server already.\n recorder.start();\n const destroy = () => {\n if (ended) return;\n ended = true;\n recorder.destroy();\n cursor.destroy();\n };\n return {\n command(command) {\n if (ended) return;\n switch (command.type) {\n case \"cursor\":\n cursor.move(\n command.at && !(\"screen\" in command.at)\n ? anchorTarget(recorder, command.at)\n : null,\n );\n return;\n case \"ripple\":\n if (!(\"screen\" in command.at))\n cursor.ripple(anchorTarget(recorder, command.at));\n return;\n case \"resync\":\n recorder.resync();\n return;\n case \"end\":\n destroy();\n return;\n default:\n }\n },\n stop(reason) {\n if (ended) return;\n destroy();\n void options.send({ type: \"end\", reason });\n },\n destroy,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,0BAAU,IAAI,IAAI;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,yBAAS,IAAI,IAAI;CACrB;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,yBAAS,IAAI,IAAI;CAAC;CAAS;CAAY;AAAQ,CAAC;;AAEtD,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAU;CAAU;CAAS;AAAO,CAAC;;AAEpE,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAQ;CAAO;CAAc;AAAY,CAAC;;AAY1E,IAAM,wBAAQ,IAAI,IAAI;CAEpB;CACA;CACA;CAEA;CACA;CAEA;CAEA;CACA;CAEA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAED,IAAM,WAA8C;CAClD,GAAG,CAAC,MAAM;CACV,MAAM,CAAC,MAAM;CACb,KAAK;EAAC;EAAO;EAAU;EAAS;CAAK;CACrC,MAAM;EAAC;EAAO;EAAQ;CAAO;CAC7B,OAAO,CAAC,OAAO;CACf,MAAM,CAAC,MAAM;CACb,IAAI;EAAC;EAAS;EAAY;CAAM;CAChC,IAAI,CAAC,MAAM;CACX,IAAI,CAAC,QAAQ,OAAO;CACpB,QAAQ,CAAC,MAAM;CACf,OAAO;EAAC;EAAS;EAAO;EAAO;EAAO;EAAQ;CAAS;CACvD,UAAU,CAAC,SAAS,KAAK;CAEzB,OAAO;EAAC;EAAQ;EAAe;EAAQ;EAAY;EAAY;CAAO;CACtE,UAAU;EAAC;EAAe;EAAQ;EAAQ;EAAY;CAAU;CAChE,QAAQ;EAAC;EAAQ;EAAY;CAAU;AACzC;;;;;;AAMA,IAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,UAAU;;AAEhB,IAAM,4BAAY,IAAI,IAAI;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAMA,WAAS;;AAEf,IAAM,+BAAe,IAAI,IAAI;CAAC;CAAU;CAAU;AAAO,CAAC;;AAG1D,SAAgB,gBAAgB,SAAkB,MAAc;CAC9D,MAAM,QAAQ,KAAK,YAAY;CAC/B,IAAI,MAAM,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,GAAG,OAAO;CACjD,IAAI,QAAQ,iBAAiBA,UAAQ,OAAO,UAAU,IAAI,KAAK;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Aa,KAAK;IAAE,MAAM;IAAO;GAAO,CAAC;GACzC,QAAQ,MAAM,MAAM;EACtB;CACF,CAAC;CAED,SAAS,MAAM;CACf,MAAM,gBAAgB;EACpB,IAAI,OAAO;EACX,QAAQ;EACR,SAAS,QAAQ;EACjB,OAAO,QAAQ;CACjB;CACA,OAAO;EACL,QAAQ,SAAS;GACf,IAAI,OAAO;GACX,QAAQ,QAAQ,MAAhB;IACE,KAAK;KACH,OAAO,KACL,QAAQ,MAAM,EAAE,YAAY,QAAQ,MAChC,aAAa,UAAU,QAAQ,EAAE,IACjC,IACN;KACA;IACF,KAAK;KACH,IAAI,EAAE,YAAY,QAAQ,KACxB,OAAO,OAAO,aAAa,UAAU,QAAQ,EAAE,CAAC;KAClD;IACF,KAAK;KACH,SAAS,OAAO;KAChB;IACF,KAAK;KACH,QAAQ;KACR;GAEJ;EACF;EACA,KAAK,QAAQ;GACX,IAAI,OAAO;GACX,QAAQ;GACR,QAAa,KAAK;IAAE,MAAM;IAAO;GAAO,CAAC;EAC3C;EACA;CACF;AACF"}
package/dist/index.js CHANGED
@@ -1,3 +1,2 @@
1
1
  "use client";
2
- import { a as useLumaAction, i as useLuma, l as defineAction, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider, t as lumaLabel } from "./chunks/src-dnp1waFV.js";
3
- export { LumaPrivate, LumaProvider, defineAction, lumaLabel, lumaPrivate, useLuma, useLumaAction, useLumaContext };
2
+ export { r as LumaPrivate, s as LumaProvider, g as defineAction, t as lumaLabel, n as lumaPrivate, i as useLuma, a as useLumaAction, o as useLumaContext } from "./chunks/src-CI0MDOrd.js";
package/dist/next.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { a as useLumaAction, c as routerPath, i as useLuma, l as defineAction, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-dnp1waFV.js";
2
+ import { a as useLumaAction, g as defineAction, h as routerPath, i as useLuma, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-CI0MDOrd.js";
3
3
  import { useMemo } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  import { useRouter } from "next/navigation";
6
- //#region src/next.tsx
6
+ // src/next.tsx
7
7
  var basePath = typeof process !== "undefined" && process.env.__NEXT_ROUTER_BASEPATH || "";
8
8
  /** LumaProvider for the Next.js App Router: navigation and guides use client-side routing. */
9
9
  function LumaProvider(props) {
@@ -17,7 +17,6 @@ function LumaProvider(props) {
17
17
  navigator
18
18
  });
19
19
  }
20
- //#endregion
21
20
  export { LumaPrivate, LumaProvider, defineAction, lumaLabel, lumaPrivate, useLuma, useLumaAction, useLumaContext };
22
21
 
23
22
  //# sourceMappingURL=next.js.map
package/dist/next.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"next.js","names":["BaseProvider"],"sources":["../src/next.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport { LumaProvider as BaseProvider, type LumaProviderProps } from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n// Next inlines its configured basePath here; router.push adds it back.\nconst basePath =\n (typeof process !== \"undefined\" && process.env.__NEXT_ROUTER_BASEPATH) || \"\";\n\n/** LumaProvider for the Next.js App Router: navigation and guides use client-side routing. */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const router = useRouter();\n const navigator = useMemo<LumaNavigation>(\n () => ({ client: true, navigate: (url) => router.push(routerPath(url, basePath)) }),\n [router],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;AAUA,IAAM,WACH,OAAO,YAAY,eAAe,QAAQ,IAAI,0BAA2B;;AAG5E,SAAgB,aAAa,OAA6C;CACxE,MAAM,SAAS,UAAU;CACzB,MAAM,YAAY,eACT;EAAE,QAAQ;EAAM,WAAW,QAAQ,OAAO,KAAK,WAAW,KAAK,QAAQ,CAAC;CAAE,IACjF,CAAC,MAAM,CACT;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
1
+ {"version":3,"file":"next.js","names":["BaseProvider"],"sources":["../src/next.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport {\n LumaProvider as BaseProvider,\n type LumaProviderProps,\n} from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n// Next inlines its configured basePath here; router.push adds it back.\nconst basePath =\n (typeof process !== \"undefined\" && process.env.__NEXT_ROUTER_BASEPATH) || \"\";\n\n/** LumaProvider for the Next.js App Router: navigation and guides use client-side routing. */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const router = useRouter();\n const navigator = useMemo<LumaNavigation>(\n () => ({\n client: true,\n navigate: (url) => router.push(routerPath(url, basePath)),\n }),\n [router],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;AAaA,IAAM,WACH,OAAO,YAAY,eAAe,QAAQ,IAAI,0BAA2B;;AAG5E,SAAgB,aAAa,OAA6C;CACxE,MAAM,SAAS,UAAU;CACzB,MAAM,YAAY,eACT;EACL,QAAQ;EACR,WAAW,QAAQ,OAAO,KAAK,WAAW,KAAK,QAAQ,CAAC;CAC1D,IACA,CAAC,MAAM,CACT;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { a as useLumaAction, c as routerPath, i as useLuma, l as defineAction, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-dnp1waFV.js";
2
+ import { a as useLumaAction, g as defineAction, h as routerPath, i as useLuma, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-CI0MDOrd.js";
3
3
  import { useMemo } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  import { useHref, useNavigate } from "react-router";
6
- //#region src/react-router.tsx
6
+ // src/react-router.tsx
7
7
  /**
8
8
  * LumaProvider for React Router 7/8 (framework, data or declarative mode). Render it inside
9
9
  * the router, e.g. in the root route component.
@@ -20,7 +20,6 @@ function LumaProvider(props) {
20
20
  navigator
21
21
  });
22
22
  }
23
- //#endregion
24
23
  export { LumaPrivate, LumaProvider, defineAction, lumaLabel, lumaPrivate, useLuma, useLumaAction, useLumaContext };
25
24
 
26
25
  //# sourceMappingURL=react-router.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"react-router.js","names":["BaseProvider"],"sources":["../src/react-router.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useHref, useNavigate } from \"react-router\";\nimport { LumaProvider as BaseProvider, type LumaProviderProps } from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n/**\n * LumaProvider for React Router 7/8 (framework, data or declarative mode). Render it inside\n * the router, e.g. in the root route component.\n */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const navigate = useNavigate();\n // navigate() prepends the basename itself.\n const basename = useHref(\"/\");\n const navigator = useMemo<LumaNavigation>(\n () => ({ client: true, navigate: (url) => void navigate(routerPath(url, basename)) }),\n [navigate, basename],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;;;;;AAaA,SAAgB,aAAa,OAA6C;CACxE,MAAM,WAAW,YAAY;CAE7B,MAAM,WAAW,QAAQ,GAAG;CAC5B,MAAM,YAAY,eACT;EAAE,QAAQ;EAAM,WAAW,QAAQ,KAAK,SAAS,WAAW,KAAK,QAAQ,CAAC;CAAE,IACnF,CAAC,UAAU,QAAQ,CACrB;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
1
+ {"version":3,"file":"react-router.js","names":["BaseProvider"],"sources":["../src/react-router.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useHref, useNavigate } from \"react-router\";\nimport {\n LumaProvider as BaseProvider,\n type LumaProviderProps,\n} from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n/**\n * LumaProvider for React Router 7/8 (framework, data or declarative mode). Render it inside\n * the router, e.g. in the root route component.\n */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const navigate = useNavigate();\n // navigate() prepends the basename itself.\n const basename = useHref(\"/\");\n const navigator = useMemo<LumaNavigation>(\n () => ({\n client: true,\n navigate: (url) => void navigate(routerPath(url, basename)),\n }),\n [navigate, basename],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;;;;;AAgBA,SAAgB,aAAa,OAA6C;CACxE,MAAM,WAAW,YAAY;CAE7B,MAAM,WAAW,QAAQ,GAAG;CAC5B,MAAM,YAAY,eACT;EACL,QAAQ;EACR,WAAW,QAAQ,KAAK,SAAS,WAAW,KAAK,QAAQ,CAAC;CAC5D,IACA,CAAC,UAAU,QAAQ,CACrB;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
package/dist/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- //#region ../assistant-contract/src/site.ts
2
+ // ../assistant-contract/src/site.ts
3
3
  var siteToolNames = [
4
4
  "siteInfo",
5
5
  "searchSite",
@@ -93,8 +93,7 @@ z.object({
93
93
  output: siteToolOutputSchema
94
94
  })).min(1).max(8)
95
95
  });
96
- //#endregion
97
- //#region src/core/actions.ts
96
+ // src/core/actions.ts
98
97
  /**
99
98
  * Define an action once and share it between the server handler (which declares it to the
100
99
  * assistant) and the page component that runs it with useLumaAction.
@@ -116,14 +115,12 @@ function actionContract(definition) {
116
115
  confirm: definition.confirm
117
116
  });
118
117
  }
119
- //#endregion
120
- //#region src/core/config.ts
118
+ // src/core/config.ts
121
119
  var API_BASE_URLS = {
122
120
  internal: "https://ir.lumai.ir/api",
123
121
  direct: "https://dash.lumai.ir/api"
124
122
  };
125
- //#endregion
126
- //#region src/server.ts
123
+ // src/server.ts
127
124
  var defaultCapabilities = [
128
125
  "siteInfo",
129
126
  "searchSite",
@@ -131,7 +128,6 @@ var defaultCapabilities = [
131
128
  "inspectPage",
132
129
  "showGuide"
133
130
  ];
134
- var firstPartyHosts = ["dash.lumai.ir", "ir.lumai.ir"];
135
131
  function json(body, status = 200, headers = {}) {
136
132
  return new Response(JSON.stringify(body), {
137
133
  status,
@@ -258,20 +254,21 @@ function createLumaSessionHandler(options) {
258
254
  log("LUMA_UPSTREAM_REJECTED", "Luma returned an unexpected session response.");
259
255
  return fail(502, "LUMA_UPSTREAM_REJECTED", "Unable to create session");
260
256
  }
261
- let avatar = typeof data.avatar === "string" && /^https?:\/\//.test(data.avatar) ? data.avatar : null;
262
- if (avatar && /^https?:\/\//.test(browserApiBaseUrl) && firstPartyHosts.includes(new URL(avatar).host)) avatar = avatar.replace(/^https?:\/\/[^/]+/, browserApiBaseUrl.replace(/\/api$/, ""));
257
+ const avatarPath = typeof data.avatarPath === "string" && data.avatarPath.startsWith("/assistant/") ? data.avatarPath : null;
258
+ const storageAvatar = typeof data.avatar === "string" && /^https?:\/\//.test(data.avatar) ? data.avatar : null;
259
+ const avatar = avatarPath && /^https?:\/\//.test(browserApiBaseUrl) ? `${browserApiBaseUrl}${avatarPath}` : storageAvatar;
263
260
  return json({
264
261
  assistantId: options.assistantId,
265
262
  sessionId: data.sessionId,
266
263
  name: typeof data.name === "string" ? data.name : "",
267
264
  color: typeof data.color === "string" ? data.color : "blue",
268
265
  avatar,
266
+ avatarPath,
269
267
  siteContext: site,
270
268
  chatEndpoint: `${browserApiBaseUrl}/assistant/chat/widget`
271
269
  });
272
270
  };
273
271
  }
274
- //#endregion
275
272
  export { createLumaSessionHandler, defineAction };
276
273
 
277
274
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../../assistant-contract/src/site.ts","../src/core/actions.ts","../src/core/config.ts","../src/server.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport const siteToolNames = [\n \"siteInfo\",\n \"searchSite\",\n \"searchProducts\",\n \"getProduct\",\n \"inspectPage\",\n \"showGuide\",\n \"navigate\",\n \"runAction\",\n] as const;\nexport type SiteToolName = (typeof siteToolNames)[number];\nconst text = z.string().trim().max(300);\nconst guideStep = z.object({\n targetId: text.min(1),\n title: text.min(1),\n description: z.string().trim().min(1).max(1200),\n completion: z.enum([\"next\", \"click\", \"change\", \"expanded\"]),\n expectedTargetId: text\n .nullable()\n .optional()\n .describe(\n \"Another observed element to verify, or null when no additional target is needed.\",\n ),\n});\nexport const siteToolInputs = {\n siteInfo: z.object({}),\n searchSite: z.object({\n query: text,\n page: z.number().int().min(1).max(1000).default(1),\n }),\n searchProducts: z.object({\n query: text,\n minPrice: z\n .number()\n .nonnegative()\n .nullable()\n .optional()\n .describe(\n \"Minimum price in store currency, or null when no minimum was requested.\",\n ),\n maxPrice: z\n .number()\n .nonnegative()\n .nullable()\n .optional()\n .describe(\n \"Maximum price in store currency, or null when no budget was requested. Zero means free products only.\",\n ),\n category: text\n .nullable()\n .optional()\n .describe(\"Known category slug, or null for all categories.\"),\n inStock: z.boolean().default(true),\n page: z.number().int().min(1).max(1000).default(1),\n }),\n getProduct: z.object({\n productId: z.union([z.number().int().positive(), text.min(1)]),\n }),\n inspectPage: z.object({ query: text.default(\"\") }),\n showGuide: guideStep,\n navigate: z.object({\n destinationId: text.min(1),\n explanation: z.string().trim().min(1).max(600),\n }),\n runAction: z.object({\n action: text.min(1),\n input: z.record(z.string(), z.unknown()),\n explanation: z.string().trim().min(1).max(600),\n }),\n};\nexport const siteActionNamePattern = /^[A-Za-z][\\w-]{0,63}$/;\nexport const siteActionSchema = z.object({\n name: z.string().regex(siteActionNamePattern),\n description: z.string().trim().min(1).max(500),\n // JSON Schema for the action input, validated again by the executing page.\n input: z\n .record(z.string(), z.unknown())\n .refine((value) => JSON.stringify(value).length <= 4000, \"Schema too large\"),\n confirm: z.boolean(),\n});\nexport type SiteAction = z.infer<typeof siteActionSchema>;\nexport const pageElementSchema = z.object({\n id: text,\n label: text,\n role: text,\n href: z.string().max(2048).optional(),\n expanded: z.boolean().optional(),\n options: z.array(text).max(30).optional(),\n});\nexport const pageSnapshotSchema = z.object({\n url: z.string().max(2048),\n title: text,\n revision: text,\n elements: z.array(pageElementSchema).max(100),\n restricted: z.boolean().optional(),\n // Structured state the website shares deliberately (React useLumaContext).\n appContext: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PageSnapshot = z.infer<typeof pageSnapshotSchema>;\nexport type GuideInput = z.infer<typeof guideStep>;\n/** showGuide input for sites announcing the guideTour feature. */\nexport const guideTourInput = z.object({\n steps: z\n .array(guideStep)\n .min(1)\n .max(8)\n .describe(\n \"Ordered steps shown in sequence on the current page without returning to you between them.\",\n ),\n});\n/** Accepts tour input and the single-step input of older servers. */\nexport function guideSteps(input: unknown): GuideInput[] | null {\n const tour = guideTourInput.safeParse(input);\n if (tour.success) return tour.data.steps;\n const step = guideStep.safeParse(input);\n return step.success ? [step.data] : null;\n}\nexport const siteFeatures = [\"guideTour\"] as const;\nexport const SITE_CONTEXT_MAX_LENGTH = 24000;\nexport const siteContextSchema = z\n .object({\n version: z.literal(1),\n origin: z.url().max(2048),\n capabilities: z.array(z.enum(siteToolNames)).max(12),\n // Optional so older plugins and servers interoperate in both directions.\n features: z.array(z.enum(siteFeatures)).max(8).optional(),\n actions: z.array(siteActionSchema).max(20).optional(),\n })\n .refine(\n (value) => JSON.stringify(value).length <= SITE_CONTEXT_MAX_LENGTH,\n \"Site context too large\",\n )\n .refine(\n (value) =>\n new Set(value.actions?.map((action) => action.name)).size ===\n (value.actions?.length ?? 0),\n \"Duplicate action names\",\n );\nexport type SiteContext = z.infer<typeof siteContextSchema>;\nexport const siteToolOutputSchema = z\n .object({\n status: z.enum([\n \"ok\",\n \"completed\",\n \"cancelled\",\n \"unavailable\",\n \"navigated\",\n \"error\",\n ]),\n data: z.unknown().optional(),\n message: z.string().max(1200).optional(),\n })\n .refine(\n (value) => JSON.stringify(value).length <= 48000,\n \"Tool output too large\",\n );\nexport type SiteToolOutput = z.infer<typeof siteToolOutputSchema>;\nexport type SiteDestination = {\n id: string;\n title: string;\n url: string;\n description?: string;\n};\nexport type SiteProduct = SiteDestination & {\n productId: number | string;\n image: string | null;\n price: string;\n currency: string;\n inStock: boolean;\n type: string;\n attributes: Record<string, string[]>;\n variations?: Array<{\n id: number | string;\n attributes: Record<string, string>;\n price: string;\n inStock: boolean;\n }>;\n};\nexport const siteContinuationSchema = z.object({\n messageId: z.string().max(100),\n results: z\n .array(\n z.object({\n toolCallId: z.string().max(200),\n output: siteToolOutputSchema,\n }),\n )\n .min(1)\n .max(8),\n});\nexport type SiteContinuation = z.infer<typeof siteContinuationSchema>;\n","import { z } from \"zod\";\nimport {\n siteActionNamePattern,\n siteActionSchema,\n type SiteAction,\n} from \"@luma/assistant-contract/site\";\n\n/** An app action the assistant may propose, such as adding a product to the cart. */\nexport type LumaActionDefinition<Input = unknown> = {\n name: string;\n /** Tells the model when to use the action. */\n description: string;\n /** Short Persian label shown to the visitor, e.g. \"افزودن به سبد خرید\". */\n title?: string;\n /** When true (default) the visitor approves every run. */\n confirm: boolean;\n input: z.ZodType<Input>;\n};\n\n/**\n * Define an action once and share it between the server handler (which declares it to the\n * assistant) and the page component that runs it with useLumaAction.\n */\nexport function defineAction<Schema extends z.ZodType>(definition: {\n name: string;\n description: string;\n title?: string;\n confirm?: boolean;\n input: Schema;\n}): LumaActionDefinition<z.output<Schema>> {\n if (!siteActionNamePattern.test(definition.name))\n throw new Error(\n `Invalid Luma action name \"${definition.name}\". Use letters, digits, \"_\" or \"-\", starting with a letter.`,\n );\n return {\n ...definition,\n confirm: definition.confirm ?? true,\n } as LumaActionDefinition<z.output<Schema>>;\n}\n\n/** The serializable declaration the assistant receives. */\nexport function actionContract(definition: LumaActionDefinition): SiteAction {\n const { $schema: _, ...input } = z.toJSONSchema(definition.input, {\n unrepresentable: \"any\",\n }) as Record<string, unknown>;\n return siteActionSchema.parse({\n name: definition.name,\n description: definition.description,\n input,\n confirm: definition.confirm,\n });\n}\n","import {\n siteContextSchema,\n type SiteContext,\n} from \"@luma/assistant-contract/site\";\nimport type { AssistantSessionData } from \"@luma/assistant-contract/protocol\";\n\nexport type ChatPosition = \"bottom-left\" | \"bottom-right\";\nexport type ChatSize = \"sm\" | \"md\" | \"lg\" | \"xl\";\nexport type IconSize = \"sm\" | \"md\" | \"lg\" | \"xl\";\n\n/** Visual options shared by the WordPress plugin settings and LumaProvider props. */\nexport type LumaAppearance = {\n position?: ChatPosition;\n size?: ChatSize;\n /** Overrides the assistant name from the dashboard. */\n title?: string;\n subtitle?: string;\n placeholder?: string;\n paddingBottom?: number;\n paddingSide?: number;\n iconSize?: IconSize;\n mobileEnabled?: boolean;\n mobileSize?: ChatSize | \"full\";\n mobilePaddingBottom?: number;\n mobilePaddingSide?: number;\n mobileIconSize?: IconSize;\n};\n\nexport const API_BASE_URLS = {\n internal: \"https://ir.lumai.ir/api\",\n direct: \"https://dash.lumai.ir/api\",\n} as const;\nexport type LumaServer = keyof typeof API_BASE_URLS;\n\n/** How the browser obtains a visitor session. */\nexport type Connection = {\n /** server: your backend (or the WordPress plugin) holds the API key. public: keyless allowed-domain session. */\n mode: \"server\" | \"public\";\n sessionEndpoint?: string;\n assistantId?: string;\n chatEndpoint?: string;\n apiBaseUrl: string;\n /** Site context fixed by the host (WordPress), instead of one negotiated per session. */\n siteContext?: SiteContext;\n /** Conversation storage namespace; one conversation per scope and tab. */\n scope: string;\n};\n\nexport type SessionData = Omit<AssistantSessionData, \"avatar\"> & {\n avatar?: string;\n assistantId?: string;\n chatEndpoint?: string;\n siteContext?: SiteContext;\n};\n/** A session with everything the chat needs, after applying connection defaults. */\nexport type ResolvedSession = SessionData & {\n assistantId: string;\n chatEndpoint: string;\n};\n\nexport function parseSession(value: unknown): SessionData {\n // The Luma API wraps the session in { success, data }; proxies return it directly.\n const raw =\n value && typeof value === \"object\" && \"data\" in value && !(\"sessionId\" in value)\n ? (value as { data: unknown }).data\n : value;\n if (\n !raw ||\n typeof raw !== \"object\" ||\n !(\"sessionId\" in raw) ||\n typeof raw.sessionId !== \"string\" ||\n !raw.sessionId.trim()\n ) {\n throw new Error(\"Invalid session response\");\n }\n const data = raw as Record<string, unknown>;\n const site = siteContextSchema.safeParse(data.siteContext);\n return {\n sessionId: raw.sessionId,\n name: typeof data.name === \"string\" ? data.name : \"دستیار هوشمند\",\n color: typeof data.color === \"string\" ? data.color : \"blue\",\n avatar:\n typeof data.avatar === \"string\" && /^https?:\\/\\//.test(data.avatar)\n ? data.avatar\n : undefined,\n ...(typeof data.assistantId === \"string\"\n ? { assistantId: data.assistantId }\n : {}),\n ...(typeof data.chatEndpoint === \"string\" &&\n /^(https?:\\/\\/|\\/)/.test(data.chatEndpoint)\n ? { chatEndpoint: data.chatEndpoint }\n : {}),\n ...(site.success ? { siteContext: site.data } : {}),\n };\n}\n","import {\n siteContextSchema,\n siteToolNames,\n type SiteToolName,\n} from \"@luma/assistant-contract/site\";\nimport { actionContract, type LumaActionDefinition } from \"./core/actions\";\nimport { API_BASE_URLS, type LumaServer } from \"./core/config\";\n\nexport { defineAction, type LumaActionDefinition } from \"./core/actions\";\n\nexport type LumaSessionHandlerOptions = {\n /** Luma API key. Keep it in a server-only environment variable. */\n apiKey: string;\n assistantId: string;\n /** Luma API host: \"internal\" (ir.lumai.ir, default) or \"direct\" (dash.lumai.ir). */\n server?: LumaServer;\n /** Overrides the API base URL this server calls, e.g. for local development. */\n apiBaseUrl?: string;\n /** API base URL visitors' browsers use for chat, when it differs from apiBaseUrl. */\n browserApiBaseUrl?: string;\n /** Public site URL. Defaults to the request's host; set it behind proxies that rewrite Host. */\n siteUrl?: string;\n /** Owner allowlist of assistant tools. Defaults to all; the page requests what it can run. */\n capabilities?: SiteToolName[];\n /** Actions the assistant may propose; pages run them with useLumaAction. */\n actions?: LumaActionDefinition[];\n /**\n * Your own visitor check or rate limit. Return false (403) or a Response to reject.\n * Sessions spend this assistant's credits, so limit them per visitor in production.\n */\n authorize?: (\n request: Request,\n ) => boolean | Response | Promise<boolean | Response>;\n fetch?: typeof fetch;\n};\n\nconst defaultCapabilities: SiteToolName[] = [\n \"siteInfo\",\n \"searchSite\",\n \"navigate\",\n \"inspectPage\",\n \"showGuide\",\n];\nconst firstPartyHosts = [\"dash.lumai.ir\", \"ir.lumai.ir\"];\n\nfunction json(body: unknown, status = 200, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store, private, max-age=0\",\n ...headers,\n },\n });\n}\n\nconst docs = \"https://dash.lumai.ir/docs/react/troubleshooting\";\n\n/** Error response with a stable code; the docs explain each one. */\nfunction fail(status: number, code: string, error: string, headers?: Record<string, string>) {\n return json({ error, code }, status, headers);\n}\n\n/** Server-side detail for the site owner; never sent to the browser. */\nfunction log(code: string, message: string) {\n console.error(`[@luma-ai/react] ${code}: ${message} See ${docs}#${code.toLowerCase()}`);\n}\n\nconst upstreamHints: Record<number, string> = {\n 400: \"Luma rejected the site context (for example, actions larger than the limits).\",\n 401: \"The API key is invalid or revoked. Create one at https://dash.lumai.ir/developers/api/keys.\",\n 404: \"The assistant was not found for this API key. Check assistantId and that the key belongs to the assistant's account.\",\n 429: \"Luma API rate limit reached.\",\n};\n\nfunction first(value: string | null) {\n return value?.split(\",\")[0]?.trim() || null;\n}\n\n/** The site origin this request belongs to, or null for a foreign browser origin. */\nfunction siteOrigin(request: Request, siteUrl?: string) {\n const origin = request.headers.get(\"origin\");\n try {\n if (siteUrl) {\n const site = new URL(siteUrl).origin;\n return origin && origin !== site ? null : site;\n }\n const url = new URL(request.url);\n const host =\n first(request.headers.get(\"x-forwarded-host\")) ??\n request.headers.get(\"host\") ??\n url.host;\n if (origin) {\n const parsed = new URL(origin);\n return parsed.host === host ? parsed.origin : null;\n }\n const protocol =\n first(request.headers.get(\"x-forwarded-proto\")) ?? url.protocol.slice(0, -1);\n return new URL(`${protocol}://${host}`).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Creates the POST handler that starts visitor sessions for LumaProvider's sessionEndpoint.\n * It uses the Fetch API, so it works as a Next.js route handler, a TanStack Start server\n * route, a React Router action, or in any runtime with Request/Response.\n */\nexport function createLumaSessionHandler(options: LumaSessionHandlerOptions) {\n const apiBaseUrl = (\n options.apiBaseUrl ?? API_BASE_URLS[options.server ?? \"internal\"]\n ).replace(/\\/+$/, \"\");\n const browserApiBaseUrl = (options.browserApiBaseUrl ?? apiBaseUrl).replace(\n /\\/+$/,\n \"\",\n );\n const allowed = new Set<SiteToolName>(options.capabilities ?? siteToolNames);\n return async function handleLumaSession(request: Request): Promise<Response> {\n if (request.method !== \"POST\")\n return fail(405, \"LUMA_METHOD_NOT_ALLOWED\", \"Method not allowed\", { Allow: \"POST\" });\n if (!options.apiKey || !options.assistantId) {\n log(\n \"LUMA_NOT_CONFIGURED\",\n `createLumaSessionHandler needs apiKey and assistantId (missing: ${[\n !options.apiKey && \"apiKey\",\n !options.assistantId && \"assistantId\",\n ]\n .filter(Boolean)\n .join(\", \")}). Set LUMA_API_KEY and LUMA_ASSISTANT_ID on the server.`,\n );\n return fail(503, \"LUMA_NOT_CONFIGURED\", \"Assistant unavailable\");\n }\n // Reject cross-site browser requests. This is not visitor authentication.\n const origin = siteOrigin(request, options.siteUrl);\n if (!origin || request.headers.get(\"sec-fetch-site\") === \"cross-site\")\n return fail(403, \"LUMA_ORIGIN_NOT_ALLOWED\", \"Origin not allowed\");\n const verdict = await options.authorize?.(request);\n if (verdict instanceof Response) return verdict;\n if (verdict === false) return fail(403, \"LUMA_FORBIDDEN\", \"Forbidden\");\n\n const text = await request.text();\n if (text.length > 16000) return fail(413, \"LUMA_INVALID_REQUEST\", \"Request too large\");\n let body: { capabilities?: unknown };\n try {\n body = text ? JSON.parse(text) : {};\n } catch {\n return fail(400, \"LUMA_INVALID_REQUEST\", \"Invalid request\");\n }\n const requested = Array.isArray(body?.capabilities)\n ? body.capabilities.filter((name): name is SiteToolName =>\n siteToolNames.includes(name as SiteToolName),\n )\n : defaultCapabilities;\n const actions = (options.actions ?? []).map(actionContract);\n const capabilities = [...new Set(requested)].filter(\n (name) => allowed.has(name) && (name !== \"runAction\" || actions.length),\n );\n const parsed = siteContextSchema.safeParse({\n version: 1,\n origin,\n capabilities,\n ...(capabilities.includes(\"showGuide\") ? { features: [\"guideTour\"] } : {}),\n ...(capabilities.includes(\"runAction\") ? { actions } : {}),\n });\n if (!parsed.success) {\n log(\n \"LUMA_INVALID_SITE_CONTEXT\",\n `The site context is invalid: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"context\"}: ${issue.message}`)\n .join(\"; \")}. Check the actions passed to createLumaSessionHandler (at most 20, schemas up to 4000 characters).`,\n );\n return fail(500, \"LUMA_INVALID_SITE_CONTEXT\", \"Assistant unavailable\");\n }\n const site = parsed.data;\n const resume = request.headers.get(\"x-session-id\");\n let response: Response;\n try {\n response = await (options.fetch ?? fetch)(\n `${apiBaseUrl}/assistant/${encodeURIComponent(options.assistantId)}/session`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"x-api-key\": options.apiKey,\n },\n body: JSON.stringify({\n site,\n ...(resume && /^[A-Za-z0-9_-]{16,200}$/.test(resume)\n ? { sessionId: resume }\n : {}),\n }),\n // Never forward the API key to a redirect target.\n redirect: \"manual\",\n cache: \"no-store\",\n signal: AbortSignal.timeout(15000),\n },\n );\n } catch (error) {\n log(\n \"LUMA_UPSTREAM_UNREACHABLE\",\n `Could not reach ${apiBaseUrl} (${error instanceof Error ? error.message : \"network error\"}). Try server: \"${options.server === \"direct\" ? \"internal\" : \"direct\"}\" if this host cannot reach it.`,\n );\n return fail(502, \"LUMA_UPSTREAM_UNREACHABLE\", \"Unable to create session\");\n }\n if (!response.ok) {\n log(\n \"LUMA_UPSTREAM_REJECTED\",\n `Luma returned HTTP ${response.status}. ${upstreamHints[response.status] ?? \"\"}`.trim(),\n );\n return fail(502, \"LUMA_UPSTREAM_REJECTED\", \"Unable to create session\");\n }\n const payload = (await response.json().catch(() => null)) as {\n success?: boolean;\n data?: Record<string, unknown>;\n } | null;\n const data = payload?.data;\n if (\n payload?.success !== true ||\n !data ||\n typeof data.sessionId !== \"string\" ||\n !data.sessionId.trim()\n ) {\n log(\"LUMA_UPSTREAM_REJECTED\", \"Luma returned an unexpected session response.\");\n return fail(502, \"LUMA_UPSTREAM_REJECTED\", \"Unable to create session\");\n }\n let avatar =\n typeof data.avatar === \"string\" && /^https?:\\/\\//.test(data.avatar)\n ? data.avatar\n : null;\n // Route first-party avatar assets through the selected server too.\n if (\n avatar &&\n /^https?:\\/\\//.test(browserApiBaseUrl) &&\n firstPartyHosts.includes(new URL(avatar).host)\n )\n avatar = avatar.replace(\n /^https?:\\/\\/[^/]+/,\n browserApiBaseUrl.replace(/\\/api$/, \"\"),\n );\n // Explicit allowlist avoids leaking future upstream response fields.\n return json({\n assistantId: options.assistantId,\n sessionId: data.sessionId,\n name: typeof data.name === \"string\" ? data.name : \"\",\n color: typeof data.color === \"string\" ? data.color : \"blue\",\n avatar,\n siteContext: site,\n chatEndpoint: `${browserApiBaseUrl}/assistant/chat/widget`,\n });\n };\n}\n"],"mappings":";;AAEA,IAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,OAAO,EAAE,OAAO,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AO,QACd,qBACA,kBAAkB,QAAQ,UAAU,EAAE,CACxC;EAEF,OAAO,KAAK;GACV,aAAa,QAAQ;GACrB,WAAW,KAAK;GAChB,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;GAClD,OAAO,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ;GACrD;GACA,aAAa;GACb,cAAc,GAAG,kBAAkB;EACrC,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../../assistant-contract/src/site.ts","../src/core/actions.ts","../src/core/config.ts","../src/server.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\nimport { z } from \"zod\";\n\nexport const siteToolNames = [\n \"siteInfo\",\n \"searchSite\",\n \"searchProducts\",\n \"getProduct\",\n \"inspectPage\",\n \"showGuide\",\n \"navigate\",\n \"runAction\",\n] as const;\nexport type SiteToolName = (typeof siteToolNames)[number];\nconst text = z.string().trim().max(300);\nconst guideStep = z.object({\n targetId: text.min(1),\n title: text.min(1),\n description: z.string().trim().min(1).max(1200),\n completion: z.enum([\"next\", \"click\", \"change\", \"expanded\"]),\n expectedTargetId: text\n .nullable()\n .optional()\n .describe(\n \"Another observed element to verify, or null when no additional target is needed.\",\n ),\n});\nexport const siteToolInputs = {\n siteInfo: z.object({}),\n searchSite: z.object({\n query: text,\n page: z.number().int().min(1).max(1000).default(1),\n }),\n searchProducts: z.object({\n query: text,\n minPrice: z\n .number()\n .nonnegative()\n .nullable()\n .optional()\n .describe(\n \"Minimum price in store currency, or null when no minimum was requested.\",\n ),\n maxPrice: z\n .number()\n .nonnegative()\n .nullable()\n .optional()\n .describe(\n \"Maximum price in store currency, or null when no budget was requested. Zero means free products only.\",\n ),\n category: text\n .nullable()\n .optional()\n .describe(\"Known category slug, or null for all categories.\"),\n inStock: z.boolean().default(true),\n page: z.number().int().min(1).max(1000).default(1),\n }),\n getProduct: z.object({\n productId: z.union([z.number().int().positive(), text.min(1)]),\n }),\n inspectPage: z.object({ query: text.default(\"\") }),\n showGuide: guideStep,\n navigate: z.object({\n destinationId: text.min(1),\n explanation: z.string().trim().min(1).max(600),\n }),\n runAction: z.object({\n action: text.min(1),\n input: z.record(z.string(), z.unknown()),\n explanation: z.string().trim().min(1).max(600),\n }),\n};\nexport const siteActionNamePattern = /^[A-Za-z][\\w-]{0,63}$/;\nexport const siteActionSchema = z.object({\n name: z.string().regex(siteActionNamePattern),\n description: z.string().trim().min(1).max(500),\n // JSON Schema for the action input, validated again by the executing page.\n input: z\n .record(z.string(), z.unknown())\n .refine(\n (value) => JSON.stringify(value).length <= 4000,\n \"Schema too large\",\n ),\n confirm: z.boolean(),\n});\nexport type SiteAction = z.infer<typeof siteActionSchema>;\nexport const pageElementSchema = z.object({\n id: text,\n label: text,\n role: text,\n href: z.string().max(2048).optional(),\n expanded: z.boolean().optional(),\n options: z.array(text).max(30).optional(),\n});\nexport const pageSnapshotSchema = z.object({\n url: z.string().max(2048),\n title: text,\n revision: text,\n elements: z.array(pageElementSchema).max(100),\n restricted: z.boolean().optional(),\n // Structured state the website shares deliberately (React useLumaContext).\n appContext: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PageSnapshot = z.infer<typeof pageSnapshotSchema>;\nexport type GuideInput = z.infer<typeof guideStep>;\n/** showGuide input for sites announcing the guideTour feature. */\nexport const guideTourInput = z.object({\n steps: z\n .array(guideStep)\n .min(1)\n .max(8)\n .describe(\n \"Ordered steps shown in sequence on the current page without returning to you between them.\",\n ),\n});\n/** Accepts tour input and the single-step input of older servers. */\nexport function guideSteps(input: unknown): GuideInput[] | null {\n const tour = guideTourInput.safeParse(input);\n if (tour.success) return tour.data.steps;\n const step = guideStep.safeParse(input);\n return step.success ? [step.data] : null;\n}\nexport const siteFeatures = [\"guideTour\"] as const;\nexport const SITE_CONTEXT_MAX_LENGTH = 24000;\nexport const siteContextSchema = z\n .object({\n version: z.literal(1),\n origin: z.url().max(2048),\n capabilities: z.array(z.enum(siteToolNames)).max(12),\n // Optional so older plugins and servers interoperate in both directions.\n features: z.array(z.enum(siteFeatures)).max(8).optional(),\n actions: z.array(siteActionSchema).max(20).optional(),\n })\n .refine(\n (value) => JSON.stringify(value).length <= SITE_CONTEXT_MAX_LENGTH,\n \"Site context too large\",\n )\n .refine(\n (value) =>\n new Set(value.actions?.map((action) => action.name)).size ===\n (value.actions?.length ?? 0),\n \"Duplicate action names\",\n );\nexport type SiteContext = z.infer<typeof siteContextSchema>;\nexport const siteToolOutputSchema = z\n .object({\n status: z.enum([\n \"ok\",\n \"completed\",\n \"cancelled\",\n \"unavailable\",\n \"navigated\",\n \"error\",\n ]),\n data: z.unknown().optional(),\n message: z.string().max(1200).optional(),\n })\n .refine(\n (value) => JSON.stringify(value).length <= 48000,\n \"Tool output too large\",\n );\nexport type SiteToolOutput = z.infer<typeof siteToolOutputSchema>;\nexport type SiteDestination = {\n id: string;\n title: string;\n url: string;\n description?: string;\n};\nexport type SiteProduct = SiteDestination & {\n productId: number | string;\n image: string | null;\n price: string;\n currency: string;\n inStock: boolean;\n type: string;\n attributes: Record<string, string[]>;\n variations?: Array<{\n id: number | string;\n attributes: Record<string, string>;\n price: string;\n inStock: boolean;\n }>;\n};\nexport const siteContinuationSchema = z.object({\n messageId: z.string().max(100),\n results: z\n .array(\n z.object({\n toolCallId: z.string().max(200),\n output: siteToolOutputSchema,\n }),\n )\n .min(1)\n .max(8),\n});\nexport type SiteContinuation = z.infer<typeof siteContinuationSchema>;\n\n/** Only outputs for existing, server-recorded pending calls can enter history. */\nexport function applySiteContinuation(\n message: UIMessage,\n continuation: SiteContinuation,\n): UIMessage {\n if (message.role !== \"assistant\" || message.id !== continuation.messageId)\n throw new Error(\"Unknown tool message\");\n const results = new Map(\n continuation.results.map((result) => [result.toolCallId, result.output]),\n );\n if (results.size !== continuation.results.length)\n throw new Error(\"Duplicate tool results\");\n const updated: UIMessage = {\n ...message,\n parts: message.parts.map((part) => {\n if (!(\"toolCallId\" in part) || !results.has(part.toolCallId)) return part;\n const name = part.type.slice(5);\n if (\n !siteToolNames.includes(name as (typeof siteToolNames)[number]) ||\n !(\"state\" in part) ||\n part.state !== \"input-available\"\n )\n throw new Error(\"Tool is not pending\");\n const output = siteToolOutputSchema.parse(results.get(part.toolCallId));\n results.delete(part.toolCallId);\n return {\n ...part,\n state: \"output-available\" as const,\n output,\n };\n }),\n };\n if (results.size) throw new Error(\"Unknown tool call\");\n if (\n updated.parts.some(\n (part) =>\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"input-available\",\n )\n )\n throw new Error(\"Incomplete tool batch\");\n return updated;\n}\n","import { z } from \"zod\";\nimport {\n siteActionNamePattern,\n siteActionSchema,\n type SiteAction,\n} from \"@luma/assistant-contract/site\";\n\n/** An app action the assistant may propose, such as adding a product to the cart. */\nexport type LumaActionDefinition<Input = unknown> = {\n name: string;\n /** Tells the model when to use the action. */\n description: string;\n /** Short Persian label shown to the visitor, e.g. \"افزودن به سبد خرید\". */\n title?: string;\n /** When true (default) the visitor approves every run. */\n confirm: boolean;\n input: z.ZodType<Input>;\n};\n\n/**\n * Define an action once and share it between the server handler (which declares it to the\n * assistant) and the page component that runs it with useLumaAction.\n */\nexport function defineAction<Schema extends z.ZodType>(definition: {\n name: string;\n description: string;\n title?: string;\n confirm?: boolean;\n input: Schema;\n}): LumaActionDefinition<z.output<Schema>> {\n if (!siteActionNamePattern.test(definition.name))\n throw new Error(\n `Invalid Luma action name \"${definition.name}\". Use letters, digits, \"_\" or \"-\", starting with a letter.`,\n );\n return {\n ...definition,\n confirm: definition.confirm ?? true,\n } as LumaActionDefinition<z.output<Schema>>;\n}\n\n/** The serializable declaration the assistant receives. */\nexport function actionContract(definition: LumaActionDefinition): SiteAction {\n const { $schema: _, ...input } = z.toJSONSchema(definition.input, {\n unrepresentable: \"any\",\n }) as Record<string, unknown>;\n return siteActionSchema.parse({\n name: definition.name,\n description: definition.description,\n input,\n confirm: definition.confirm,\n });\n}\n","import {\n siteContextSchema,\n type SiteContext,\n} from \"@luma/assistant-contract/site\";\nimport type { AssistantSessionData } from \"@luma/assistant-contract/protocol\";\n\nexport type ChatPosition = \"bottom-left\" | \"bottom-right\";\nexport type ChatSize = \"sm\" | \"md\" | \"lg\" | \"xl\";\nexport type IconSize = \"sm\" | \"md\" | \"lg\" | \"xl\";\n\n/** Visual options shared by the WordPress plugin settings and LumaProvider props. */\nexport type LumaAppearance = {\n position?: ChatPosition;\n size?: ChatSize;\n /** Overrides the assistant name from the dashboard. */\n title?: string;\n subtitle?: string;\n placeholder?: string;\n paddingBottom?: number;\n paddingSide?: number;\n iconSize?: IconSize;\n mobileEnabled?: boolean;\n mobileSize?: ChatSize | \"full\";\n mobilePaddingBottom?: number;\n mobilePaddingSide?: number;\n mobileIconSize?: IconSize;\n};\n\nexport const API_BASE_URLS = {\n internal: \"https://ir.lumai.ir/api\",\n direct: \"https://dash.lumai.ir/api\",\n} as const;\nexport type LumaServer = keyof typeof API_BASE_URLS;\n\n/** How the browser obtains a visitor session. */\nexport type Connection = {\n /** server: your backend (or the WordPress plugin) holds the API key. public: keyless allowed-domain session. */\n mode: \"server\" | \"public\";\n sessionEndpoint?: string;\n assistantId?: string;\n chatEndpoint?: string;\n apiBaseUrl: string;\n /** Site context fixed by the host (WordPress), instead of one negotiated per session. */\n siteContext?: SiteContext;\n /** Conversation storage namespace; one conversation per scope and tab. */\n scope: string;\n};\n\nexport type SessionData = Omit<\n AssistantSessionData,\n \"avatar\" | \"avatarPath\"\n> & {\n avatar?: string;\n /** The logo on the API, relative to its base (`/assistant/…`). */\n avatarPath?: string;\n assistantId?: string;\n chatEndpoint?: string;\n siteContext?: SiteContext;\n};\n/** A session with everything the chat needs, after applying connection defaults. */\nexport type ResolvedSession = SessionData & {\n assistantId: string;\n chatEndpoint: string;\n};\n\nexport function parseSession(value: unknown): SessionData {\n // The Luma API wraps the session in { success, data }; proxies return it directly.\n const raw =\n value &&\n typeof value === \"object\" &&\n \"data\" in value &&\n !(\"sessionId\" in value)\n ? (value as { data: unknown }).data\n : value;\n if (\n !raw ||\n typeof raw !== \"object\" ||\n !(\"sessionId\" in raw) ||\n typeof raw.sessionId !== \"string\" ||\n !raw.sessionId.trim()\n ) {\n throw new Error(\"Invalid session response\");\n }\n const data = raw as Record<string, unknown>;\n const site = siteContextSchema.safeParse(data.siteContext);\n return {\n sessionId: raw.sessionId,\n name: typeof data.name === \"string\" ? data.name : \"دستیار هوشمند\",\n color: typeof data.color === \"string\" ? data.color : \"blue\",\n avatar:\n typeof data.avatar === \"string\" && /^https?:\\/\\//.test(data.avatar)\n ? data.avatar\n : undefined,\n ...(typeof data.avatarPath === \"string\" &&\n data.avatarPath.startsWith(\"/assistant/\")\n ? { avatarPath: data.avatarPath }\n : {}),\n ...(typeof data.assistantId === \"string\"\n ? { assistantId: data.assistantId }\n : {}),\n ...(typeof data.chatEndpoint === \"string\" &&\n /^(https?:\\/\\/|\\/)/.test(data.chatEndpoint)\n ? { chatEndpoint: data.chatEndpoint }\n : {}),\n ...(site.success ? { siteContext: site.data } : {}),\n };\n}\n","import {\n siteContextSchema,\n siteToolNames,\n type SiteToolName,\n} from \"@luma/assistant-contract/site\";\nimport { actionContract, type LumaActionDefinition } from \"./core/actions\";\nimport { API_BASE_URLS, type LumaServer } from \"./core/config\";\n\nexport { defineAction, type LumaActionDefinition } from \"./core/actions\";\n\nexport type LumaSessionHandlerOptions = {\n /** Luma API key. Keep it in a server-only environment variable. */\n apiKey: string;\n assistantId: string;\n /** Luma API host: \"internal\" (ir.lumai.ir, default) or \"direct\" (dash.lumai.ir). */\n server?: LumaServer;\n /** Overrides the API base URL this server calls, e.g. for local development. */\n apiBaseUrl?: string;\n /** API base URL visitors' browsers use for chat, when it differs from apiBaseUrl. */\n browserApiBaseUrl?: string;\n /** Public site URL. Defaults to the request's host; set it behind proxies that rewrite Host. */\n siteUrl?: string;\n /** Owner allowlist of assistant tools. Defaults to all; the page requests what it can run. */\n capabilities?: SiteToolName[];\n /** Actions the assistant may propose; pages run them with useLumaAction. */\n actions?: LumaActionDefinition[];\n /**\n * Your own visitor check or rate limit. Return false (403) or a Response to reject.\n * Sessions spend this assistant's credits, so limit them per visitor in production.\n */\n authorize?: (\n request: Request,\n ) => boolean | Response | Promise<boolean | Response>;\n fetch?: typeof fetch;\n};\n\nconst defaultCapabilities: SiteToolName[] = [\n \"siteInfo\",\n \"searchSite\",\n \"navigate\",\n \"inspectPage\",\n \"showGuide\",\n];\n\nfunction json(\n body: unknown,\n status = 200,\n headers: Record<string, string> = {},\n) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store, private, max-age=0\",\n ...headers,\n },\n });\n}\n\nconst docs = \"https://dash.lumai.ir/docs/react/troubleshooting\";\n\n/** Error response with a stable code; the docs explain each one. */\nfunction fail(\n status: number,\n code: string,\n error: string,\n headers?: Record<string, string>,\n) {\n return json({ error, code }, status, headers);\n}\n\n/** Server-side detail for the site owner; never sent to the browser. */\nfunction log(code: string, message: string) {\n console.error(\n `[@luma-ai/react] ${code}: ${message} See ${docs}#${code.toLowerCase()}`,\n );\n}\n\nconst upstreamHints: Record<number, string> = {\n 400: \"Luma rejected the site context (for example, actions larger than the limits).\",\n 401: \"The API key is invalid or revoked. Create one at https://dash.lumai.ir/developers/api/keys.\",\n 404: \"The assistant was not found for this API key. Check assistantId and that the key belongs to the assistant's account.\",\n 429: \"Luma API rate limit reached.\",\n};\n\nfunction first(value: string | null) {\n return value?.split(\",\")[0]?.trim() || null;\n}\n\n/** The site origin this request belongs to, or null for a foreign browser origin. */\nfunction siteOrigin(request: Request, siteUrl?: string) {\n const origin = request.headers.get(\"origin\");\n try {\n if (siteUrl) {\n const site = new URL(siteUrl).origin;\n return origin && origin !== site ? null : site;\n }\n const url = new URL(request.url);\n const host =\n first(request.headers.get(\"x-forwarded-host\")) ??\n request.headers.get(\"host\") ??\n url.host;\n if (origin) {\n const parsed = new URL(origin);\n return parsed.host === host ? parsed.origin : null;\n }\n const protocol =\n first(request.headers.get(\"x-forwarded-proto\")) ??\n url.protocol.slice(0, -1);\n return new URL(`${protocol}://${host}`).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Creates the POST handler that starts visitor sessions for LumaProvider's sessionEndpoint.\n * It uses the Fetch API, so it works as a Next.js route handler, a TanStack Start server\n * route, a React Router action, or in any runtime with Request/Response.\n */\nexport function createLumaSessionHandler(options: LumaSessionHandlerOptions) {\n const apiBaseUrl = (\n options.apiBaseUrl ?? API_BASE_URLS[options.server ?? \"internal\"]\n ).replace(/\\/+$/, \"\");\n const browserApiBaseUrl = (options.browserApiBaseUrl ?? apiBaseUrl).replace(\n /\\/+$/,\n \"\",\n );\n const allowed = new Set<SiteToolName>(options.capabilities ?? siteToolNames);\n return async function handleLumaSession(request: Request): Promise<Response> {\n if (request.method !== \"POST\")\n return fail(405, \"LUMA_METHOD_NOT_ALLOWED\", \"Method not allowed\", {\n Allow: \"POST\",\n });\n if (!options.apiKey || !options.assistantId) {\n log(\n \"LUMA_NOT_CONFIGURED\",\n `createLumaSessionHandler needs apiKey and assistantId (missing: ${[\n !options.apiKey && \"apiKey\",\n !options.assistantId && \"assistantId\",\n ]\n .filter(Boolean)\n .join(\", \")}). Set LUMA_API_KEY and LUMA_ASSISTANT_ID on the server.`,\n );\n return fail(503, \"LUMA_NOT_CONFIGURED\", \"Assistant unavailable\");\n }\n // Reject cross-site browser requests. This is not visitor authentication.\n const origin = siteOrigin(request, options.siteUrl);\n if (!origin || request.headers.get(\"sec-fetch-site\") === \"cross-site\")\n return fail(403, \"LUMA_ORIGIN_NOT_ALLOWED\", \"Origin not allowed\");\n const verdict = await options.authorize?.(request);\n if (verdict instanceof Response) return verdict;\n if (verdict === false) return fail(403, \"LUMA_FORBIDDEN\", \"Forbidden\");\n\n const text = await request.text();\n if (text.length > 16000)\n return fail(413, \"LUMA_INVALID_REQUEST\", \"Request too large\");\n let body: { capabilities?: unknown };\n try {\n body = text ? JSON.parse(text) : {};\n } catch {\n return fail(400, \"LUMA_INVALID_REQUEST\", \"Invalid request\");\n }\n const requested = Array.isArray(body?.capabilities)\n ? body.capabilities.filter((name): name is SiteToolName =>\n siteToolNames.includes(name as SiteToolName),\n )\n : defaultCapabilities;\n const actions = (options.actions ?? []).map(actionContract);\n const capabilities = [...new Set(requested)].filter(\n (name) => allowed.has(name) && (name !== \"runAction\" || actions.length),\n );\n const parsed = siteContextSchema.safeParse({\n version: 1,\n origin,\n capabilities,\n ...(capabilities.includes(\"showGuide\")\n ? { features: [\"guideTour\"] }\n : {}),\n ...(capabilities.includes(\"runAction\") ? { actions } : {}),\n });\n if (!parsed.success) {\n log(\n \"LUMA_INVALID_SITE_CONTEXT\",\n `The site context is invalid: ${parsed.error.issues\n .map(\n (issue) => `${issue.path.join(\".\") || \"context\"}: ${issue.message}`,\n )\n .join(\n \"; \",\n )}. Check the actions passed to createLumaSessionHandler (at most 20, schemas up to 4000 characters).`,\n );\n return fail(500, \"LUMA_INVALID_SITE_CONTEXT\", \"Assistant unavailable\");\n }\n const site = parsed.data;\n const resume = request.headers.get(\"x-session-id\");\n let response: Response;\n try {\n response = await (options.fetch ?? fetch)(\n `${apiBaseUrl}/assistant/${encodeURIComponent(options.assistantId)}/session`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"x-api-key\": options.apiKey,\n },\n body: JSON.stringify({\n site,\n ...(resume && /^[A-Za-z0-9_-]{16,200}$/.test(resume)\n ? { sessionId: resume }\n : {}),\n }),\n // Never forward the API key to a redirect target.\n redirect: \"manual\",\n cache: \"no-store\",\n signal: AbortSignal.timeout(15000),\n },\n );\n } catch (error) {\n log(\n \"LUMA_UPSTREAM_UNREACHABLE\",\n `Could not reach ${apiBaseUrl} (${error instanceof Error ? error.message : \"network error\"}). Try server: \"${options.server === \"direct\" ? \"internal\" : \"direct\"}\" if this host cannot reach it.`,\n );\n return fail(502, \"LUMA_UPSTREAM_UNREACHABLE\", \"Unable to create session\");\n }\n if (!response.ok) {\n log(\n \"LUMA_UPSTREAM_REJECTED\",\n `Luma returned HTTP ${response.status}. ${upstreamHints[response.status] ?? \"\"}`.trim(),\n );\n return fail(502, \"LUMA_UPSTREAM_REJECTED\", \"Unable to create session\");\n }\n const payload = (await response.json().catch(() => null)) as {\n success?: boolean;\n data?: Record<string, unknown>;\n } | null;\n const data = payload?.data;\n if (\n payload?.success !== true ||\n !data ||\n typeof data.sessionId !== \"string\" ||\n !data.sessionId.trim()\n ) {\n log(\n \"LUMA_UPSTREAM_REJECTED\",\n \"Luma returned an unexpected session response.\",\n );\n return fail(502, \"LUMA_UPSTREAM_REJECTED\", \"Unable to create session\");\n }\n // The logo through the API visitors use (2.0.0): never the storage host,\n // which a visitor's network may not reach. Older servers send only the\n // storage address.\n const avatarPath =\n typeof data.avatarPath === \"string\" &&\n data.avatarPath.startsWith(\"/assistant/\")\n ? data.avatarPath\n : null;\n const storageAvatar =\n typeof data.avatar === \"string\" && /^https?:\\/\\//.test(data.avatar)\n ? data.avatar\n : null;\n const avatar =\n avatarPath && /^https?:\\/\\//.test(browserApiBaseUrl)\n ? `${browserApiBaseUrl}${avatarPath}`\n : storageAvatar;\n // Explicit allowlist avoids leaking future upstream response fields.\n return json({\n assistantId: options.assistantId,\n sessionId: data.sessionId,\n name: typeof data.name === \"string\" ? data.name : \"\",\n color: typeof data.color === \"string\" ? data.color : \"blue\",\n avatar,\n avatarPath,\n siteContext: site,\n chatEndpoint: `${browserApiBaseUrl}/assistant/chat/widget`,\n });\n };\n}\n"],"mappings":";;AAGA,IAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG;AACtC,IAAM,YAAY,EAAE,OAAO;CACzB,UAAU,KAAK,IAAI,CAAC;CACpB,OAAO,KAAK,IAAI,CAAC;CACjB,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,I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 -1,9 +1,9 @@
1
1
  "use client";
2
- import { a as useLumaAction, c as routerPath, i as useLuma, l as defineAction, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-dnp1waFV.js";
2
+ import { a as useLumaAction, g as defineAction, h as routerPath, i as useLuma, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-CI0MDOrd.js";
3
3
  import { useMemo } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  import { useRouter } from "@tanstack/react-router";
6
- //#region src/tanstack.tsx
6
+ // src/tanstack.tsx
7
7
  /** LumaProvider for TanStack Router and TanStack Start. Render it inside the router (root route). */
8
8
  function LumaProvider(props) {
9
9
  const router = useRouter();
@@ -16,7 +16,6 @@ function LumaProvider(props) {
16
16
  navigator
17
17
  });
18
18
  }
19
- //#endregion
20
19
  export { LumaPrivate, LumaProvider, defineAction, lumaLabel, lumaPrivate, useLuma, useLumaAction, useLumaContext };
21
20
 
22
21
  //# sourceMappingURL=tanstack.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack.js","names":["BaseProvider"],"sources":["../src/tanstack.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useRouter } from \"@tanstack/react-router\";\nimport { LumaProvider as BaseProvider, type LumaProviderProps } from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n/** LumaProvider for TanStack Router and TanStack Start. Render it inside the router (root route). */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const router = useRouter();\n const navigator = useMemo<LumaNavigation>(\n // href is the public URL, including any basepath.\n () => ({ client: true, navigate: (url) => void router.navigate({ href: routerPath(url) }) }),\n [router],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;;AAUA,SAAgB,aAAa,OAA6C;CACxE,MAAM,SAAS,UAAU;CACzB,MAAM,YAAY,eAET;EAAE,QAAQ;EAAM,WAAW,QAAQ,KAAK,OAAO,SAAS,EAAE,MAAM,WAAW,GAAG,EAAE,CAAC;CAAE,IAC1F,CAAC,MAAM,CACT;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
1
+ {"version":3,"file":"tanstack.js","names":["BaseProvider"],"sources":["../src/tanstack.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useRouter } from \"@tanstack/react-router\";\nimport {\n LumaProvider as BaseProvider,\n type LumaProviderProps,\n} from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n/** LumaProvider for TanStack Router and TanStack Start. Render it inside the router (root route). */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const router = useRouter();\n const navigator = useMemo<LumaNavigation>(\n // href is the public URL, including any basepath.\n () => ({\n client: true,\n navigate: (url) => void router.navigate({ href: routerPath(url) }),\n }),\n [router],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,aAAa,OAA6C;CACxE,MAAM,SAAS,UAAU;CACzB,MAAM,YAAY,eAET;EACL,QAAQ;EACR,WAAW,QAAQ,KAAK,OAAO,SAAS,EAAE,MAAM,WAAW,GAAG,EAAE,CAAC;CACnE,IACA,CAAC,MAAM,CACT;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
package/docs/ai-agents.md CHANGED
@@ -11,11 +11,11 @@ description: مستندات Markdown، llms.txt، فایل‌های داخل nod
11
11
 
12
12
  ## مستندات Markdown
13
13
 
14
- | آدرس | محتوا |
15
- | --- | --- |
16
- | `https://dash.lumai.ir/llms.txt` | فهرست مستندات با لینک نسخه Markdown هر صفحه ([llms.txt](https://llmstxt.org)) |
17
- | `https://dash.lumai.ir/llms-full.txt` | همه مستندات در یک فایل |
18
- | `https://dash.lumai.ir/docs/react/<صفحه>.md` | نسخه Markdown هر صفحه، مثلاً `/docs/react/actions.md` |
14
+ | آدرس | محتوا |
15
+ | -------------------------------------------- | ----------------------------------------------------------------------------- |
16
+ | `https://dash.lumai.ir/llms.txt` | فهرست مستندات با لینک نسخه Markdown هر صفحه ([llms.txt](https://llmstxt.org)) |
17
+ | `https://dash.lumai.ir/llms-full.txt` | همه مستندات در یک فایل |
18
+ | `https://dash.lumai.ir/docs/react/<صفحه>.md` | نسخه Markdown هر صفحه، مثلاً `/docs/react/actions.md` |
19
19
 
20
20
  درخواست صفحه‌های مستندات با هدر `Accept: text/markdown` هم به‌جای HTML، Markdown برمی‌گرداند.
21
21